file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
UpdateService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/update/UpdateService.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.update; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import javafx.beans.property.BooleanProperty; import javafx.beans.property.Property; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import moe.lyrebird.model.update.client.LyrebirdServerClient; import moe.lyrebird.api.model.LyrebirdVersion; import moe.lyrebird.model.interrupts.CleanupOperation; import moe.lyrebird.model.interrupts.CleanupService; import moe.lyrebird.model.notifications.Notification; import moe.lyrebird.model.notifications.NotificationService; import moe.lyrebird.model.notifications.NotificationSystemType; import moe.lyrebird.model.update.selfupdate.SelfupdateService; /** * The update service takes care of all things related to update check and installation */ @Component public class UpdateService { private static final Logger LOG = LoggerFactory.getLogger(UpdateService.class); private static final ScheduledExecutorService EXECUTOR = Executors.newSingleThreadScheduledExecutor(); private static final Pattern BUILD_VERSION_PATTERN = Pattern.compile("\\."); private final LyrebirdServerClient apiClient; private final NotificationService notificationService; private final SelfupdateService selfupdateService; private final CleanupService cleanupService; private final String currentVersion; private final int currentBuildVersion; private final BooleanProperty isUpdateAvailable = new SimpleBooleanProperty(false); private final Property<LyrebirdVersion> latestVersion = new SimpleObjectProperty<>(null); public UpdateService( final LyrebirdServerClient apiClient, final NotificationService notificationService, final SelfupdateService selfupdateService, final Environment environment, final CleanupService cleanupService ) { this.apiClient = apiClient; this.notificationService = notificationService; this.selfupdateService = selfupdateService; this.currentVersion = environment.getRequiredProperty("app.version"); this.cleanupService = cleanupService; this.currentBuildVersion = getCurrentBuildVersion(); this.isUpdateAvailable.addListener((o, prev, cur) -> handleUpdateStatus(prev, cur)); startPolling(); } /** * @return the asynchronously fetched last version according to the API */ public CompletableFuture<LyrebirdVersion> getLatestVersion() { return CompletableFuture.supplyAsync(() -> { if (latestVersion.getValue() == null) { poll(); } return latestVersion.getValue(); }); } public BooleanProperty isUpdateAvailableProperty() { return isUpdateAvailable; } /** * @return the asynchronously fetched changenotes for the latest version */ public CompletableFuture<String> getLatestChangeNotes() { return CompletableFuture.supplyAsync( () -> apiClient.getChangeNotes(latestVersion.getValue().getBuildVersion()) ); } /** * Starts self-updating to the latest version available */ public void selfupdate() { getLatestVersion().thenAcceptAsync(selfupdateService::selfupdate); } /** * @return whether the current platform supports self-updating */ public static boolean selfupdateCompatible() { return SelfupdateService.selfupdateCompatible(); } /** * Starts the scheduled check for updates */ private void startPolling() { EXECUTOR.scheduleAtFixedRate( this::poll, 10L, 5L * 60L, TimeUnit.SECONDS ); cleanupService.registerCleanupOperation(new CleanupOperation( "Stop update service", EXECUTOR::shutdownNow )); } /** * Fetches the latest version and sets it in {@link #latestVersion}. If this version has a newer {@link * LyrebirdVersion#getBuildVersion()} than the current one, set {@link #isUpdateAvailable} to true */ private void poll() { try { LOG.debug("Checking for updates..."); final LyrebirdVersion latestVersionServer = apiClient.getLatestVersion(); LOG.debug("Latest version : {}", latestVersionServer.getVersion()); this.latestVersion.setValue(latestVersionServer); isUpdateAvailable.setValue(latestVersionServer.getBuildVersion() > currentBuildVersion); } catch (final Exception e) { LOG.error("Could not check for updates !", e); } } /** * @return the buildVersion of the currently running application */ private int getCurrentBuildVersion() { final String formatted = BUILD_VERSION_PATTERN.matcher(currentVersion).replaceAll(""); return Integer.parseInt(formatted); } /** * Handles changes to {@link #isUpdateAvailable}. If it becomes true, we notify the user via the OS of the * availability of the update. * * @param prev previous status * @param cur new status */ private void handleUpdateStatus(final boolean prev, final boolean cur) { if (cur && !prev) { LOG.debug("An update was detected. Notifying the user."); notificationService.sendNotification( new Notification( "Update available!", "An update is available for Lyrebird, grab it :-)" ), NotificationSystemType.SYSTEM ); } else if (!cur) { LOG.debug("No update available."); } } }
6,919
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
PostUpdateCompatibilityTasks.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/update/compatibility/PostUpdateCompatibilityTasks.java
package moe.lyrebird.model.update.compatibility; import java.io.File; import java.util.List; public enum PostUpdateCompatibilityTasks implements PostUpdateCompatibilityTask { WIPE_DB( "Wipe Lyrebird database", List.of("1.1.2-twitter4j-to-twitter4a-hibernate", "1.1.4-twitter4a-to-twitter4j-hibernate"), () -> deleteIfExists(".lyrebird") ); private final String name; private final List<String> reasonsToExecute; private final Runnable execution; PostUpdateCompatibilityTasks(String name, List<String> reasonsToExecute, Runnable execution) { this.name = name; this.reasonsToExecute = reasonsToExecute; this.execution = execution; } @Override public String getName() { return name; } @Override public List<String> getReasonsToExecute() { return reasonsToExecute; } @Override public Runnable getExecution() { return execution; } private static void deleteIfExists(final String pathRelativeToUserHome) { final File toDelete = new File(System.getProperty("user.home"), pathRelativeToUserHome); if (toDelete.exists()) { try { assert toDelete.delete() : "Could not delete " + toDelete.getAbsolutePath() + " for compatibility!"; } catch (AssertionError error) { throw new IllegalStateException(error); } } } }
1,459
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
PostUpdateCompatibilityTask.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/update/compatibility/PostUpdateCompatibilityTask.java
package moe.lyrebird.model.update.compatibility; import java.util.List; import java.util.prefs.Preferences; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.vavr.control.Option; interface PostUpdateCompatibilityTask { Logger LOG = LoggerFactory.getLogger(PostUpdateCompatibilityTask.class); Preferences USER_PREFERENCES = Preferences.userRoot().node("Lyrebird"); String getName(); List<String> getReasonsToExecute(); Runnable getExecution(); default Option<Runnable> getRequiredExecution() { LOG.debug("-> {}", getName()); LOG.debug("\tChecking for the following reasons {}", getReasonsToExecute()); final List<String> unfulfilled = getUnfulfilled(getReasonsToExecute()); if (unfulfilled.isEmpty()) { return Option.of(() -> LOG.debug( "\tNo need for execution of {} as reasons all fulfilled : {}", getName(), getReasonsToExecute() )); } else { return Option.of(() -> { LOG.debug("\tNeed to execute {} due to {}", getName(), unfulfilled); getExecution().run(); LOG.debug("\tExecuted! Setting reasons {} to fulfilled.", unfulfilled); unfulfilled.forEach(reason -> USER_PREFERENCES.putBoolean(reason, true)); }); } } private static List<String> getUnfulfilled(final List<String> reasonsToCheck) { return reasonsToCheck.stream() .filter(reason -> !USER_PREFERENCES.getBoolean(reason, false)) .collect(Collectors.toList()); } }
1,710
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
PostUpdateCompatibilityHelper.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/update/compatibility/PostUpdateCompatibilityHelper.java
package moe.lyrebird.model.update.compatibility; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.vavr.control.Option; public final class PostUpdateCompatibilityHelper { private static final Logger LOG = LoggerFactory.getLogger(PostUpdateCompatibilityHelper.class); private PostUpdateCompatibilityHelper() { } public static void executeCompatibilityTasks() { LOG.debug("Parsing post-update compatibility tasks."); Arrays.stream(PostUpdateCompatibilityTasks.values()) .map(PostUpdateCompatibilityTask::getRequiredExecution) .flatMap(Option::toJavaStream) .forEach(Runnable::run); } }
712
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
LyrebirdServerClientInterceptor.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/update/client/LyrebirdServerClientInterceptor.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.update.client; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.lang.NonNull; public class LyrebirdServerClientInterceptor implements ClientHttpRequestInterceptor { private static final Logger LOG = LoggerFactory.getLogger(LyrebirdServerClientInterceptor.class); @NonNull @Override public ClientHttpResponse intercept( @NonNull final HttpRequest request, @NonNull final byte[] body, @NonNull final ClientHttpRequestExecution execution ) throws IOException { LOG.debug("{} => {}", request.getMethod(), request.getURI()); return execution.execute(request, body); } }
1,789
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
LyrebirdServerClient.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/update/client/LyrebirdServerClient.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.update.client; import static moe.lyrebird.api.conf.Endpoints.VERSIONS_CHANGENOTES; import static moe.lyrebird.api.conf.Endpoints.VERSIONS_CONTROLLER; import static moe.lyrebird.api.conf.Endpoints.VERSIONS_LATEST; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import moe.lyrebird.api.model.LyrebirdVersion; @Component public class LyrebirdServerClient { private static final Logger LOG = LoggerFactory.getLogger(LyrebirdServerClient.class); private final RestTemplate restTemplate; private final String apiUrl; @Autowired public LyrebirdServerClient(final Environment environment) { this.restTemplate = new RestTemplate(); this.restTemplate.getInterceptors().add(new LyrebirdServerClientInterceptor()); this.apiUrl = environment.getRequiredProperty("api.url"); } public LyrebirdVersion getLatestVersion() { LOG.info("Loading latest version from server"); return restTemplate.getForEntity( buildUrl(VERSIONS_CONTROLLER, VERSIONS_LATEST), LyrebirdVersion.class ).getBody(); } @Cacheable(value = "buildVersionChaneNotes", sync = true) public String getChangeNotes(final int buildVersion) { LOG.info("Loading changenotes for buildVersion {}", buildVersion); return restTemplate.getForObject( buildUrl(VERSIONS_CONTROLLER, VERSIONS_CHANGENOTES), String.class, buildVersion ); } private String buildUrl(final String controller, final String method) { return apiUrl + "/" + controller + "/" + method; } }
2,738
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
SelfupdateService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/update/selfupdate/SelfupdateService.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.update.selfupdate; import java.io.IOException; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.stage.Stage; import moe.lyrebird.api.model.LyrebirdVersion; import moe.lyrebird.api.model.TargetPlatform; import moe.lyrebird.view.screens.root.RootScreenComponent; import moe.tristan.easyfxml.model.beanmanagement.StageManager; import io.vavr.control.Option; /** * This service is in charge of the orchestration of the selfupdate process */ @Component public class SelfupdateService { private static final Logger LOG = LoggerFactory.getLogger(SelfupdateService.class); private final StageManager stageManager; private final RootScreenComponent rootScreenComponent; @Autowired public SelfupdateService(final StageManager stageManager, RootScreenComponent rootScreenComponent) { this.stageManager = stageManager; this.rootScreenComponent = rootScreenComponent; } /** * Starts the selfupdate process to the given target version * * @param newVersion the version to which to selfupdate */ public void selfupdate(final LyrebirdVersion newVersion) { LOG.info("Requesting selfupdate to version : {}", newVersion); Platform.runLater(SelfupdateService::displayUpdateDownloadAlert); CompletableFuture.supplyAsync(SelfupdateService::getTargetPlatform) .thenApplyAsync(platform -> BinaryInstallationService.getInstallationCommandLine( platform, newVersion )) .thenAcceptAsync(this::launchUpdate, Platform::runLater); } public static boolean selfupdateCompatible() { return BinaryChoiceService.currentPlatformSupportsSelfupdate(); } private void launchUpdate(final String[] exec) { stageManager.getSingle(rootScreenComponent).peek(Stage::close); SelfupdateService.displayRestartAlert(); SelfupdateService.installNewVersion(exec); System.exit(0); } private static TargetPlatform getTargetPlatform() { final Option<TargetPlatform> executablePlatform = BinaryChoiceService.detectRunningPlatform(); if (executablePlatform.isEmpty()) { LOG.error("Lyrebird does not currently support self-updating on this platform!"); throw new UnsupportedOperationException("Cannot selfupdate with current binary platform!"); } return executablePlatform.get(); } /** * Launches an OS-level process to install the new version of Lyrebird * * @param executable The system executable update installation command */ private static void installNewVersion(final String[] executable) { LOG.info("Executing : {}", (Object) executable); final ProcessBuilder installProcess = new ProcessBuilder(executable); installProcess.redirectError(ProcessBuilder.Redirect.INHERIT); installProcess.redirectOutput(ProcessBuilder.Redirect.INHERIT); try { installProcess.start(); } catch (final IOException e) { LOG.error("Cannot start installation.", e); } } private static void displayUpdateDownloadAlert() { final Alert selfupdateStartedAlert = new Alert( Alert.AlertType.CONFIRMATION, "Started downloading update in the background. We will tell you when it is ready !", ButtonType.OK ); selfupdateStartedAlert.showAndWait(); } /** * Displays an alert to the user informing them that the selfupdate is ready to start and they need to restart the application after we automatically stop * it. */ private static void displayRestartAlert() { LOG.debug("Displaying restart information alert!"); final Alert restartAlert = new Alert( Alert.AlertType.INFORMATION, "Lyrebird has downloaded the update! " + "The application will automatically quit and start updating!", ButtonType.OK ); restartAlert.showAndWait(); } }
5,275
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
BinaryChoiceService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/update/selfupdate/BinaryChoiceService.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.update.selfupdate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import moe.lyrebird.api.model.TargetPlatform; import io.vavr.control.Option; import oshi.SystemInfo; /** * This service helps choose the right package type for the current platform. */ public final class BinaryChoiceService { private static final Logger LOG = LoggerFactory.getLogger(BinaryChoiceService.class); private BinaryChoiceService() { } static boolean currentPlatformSupportsSelfupdate() { return detectRunningPlatform().isDefined(); } /** * Maps the current platform with a Lyrebird package type platform. * * @return the appropriate {@link TargetPlatform} for the current platform if supported. If the current platform is * not specifically supported, returns {@link Option#none()}. */ static Option<TargetPlatform> detectRunningPlatform() { LOG.debug("Detecting platform..."); switch (SystemInfo.getCurrentPlatformEnum()) { case WINDOWS: LOG.debug("Running on Windows"); return Option.of(TargetPlatform.WINDOWS); case LINUX: LOG.debug("Running on Linux."); return Option.none(); case MACOSX: LOG.debug("Running on macOS."); return Option.of(TargetPlatform.MACOS); case SOLARIS: case FREEBSD: case UNKNOWN: default: LOG.debug("Unknown platform : {}", SystemInfo.getCurrentPlatformEnum()); return Option.none(); } } }
2,455
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
BinaryInstallationHelper.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/update/selfupdate/BinaryInstallationHelper.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.update.selfupdate; import org.springframework.util.StreamUtils; import moe.lyrebird.Lyrebird; import moe.lyrebird.api.model.TargetPlatform; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; /** * This helper class builds the required command line setup to selfupdate on supported platforms. * <p> * Largely based off of <pre>https://github.com/bitgamma/updatefx/blob/master/src/main/java/com/briksoftware/updatefx * /core/InstallerService.java</pre> */ final class BinaryInstallationHelper { private static final String TEMP_FOLDER = System.getProperty("java.io.tmpdir"); private static final String LYREBIRD_DL_FOLDER = "lyrebird"; private BinaryInstallationHelper() { throw new IllegalStateException("Not instantiable class."); } /** * Selects the appropriate command line argument generation method for the given platform. * * @param targetPlatform The platform for which to generate command line arguments * @param file The file for which to generate command line arguments * * @return The appropriate selfupdate command line arguments for the given platform and package file */ static String[] generateCommandLineForPlatformWithFile( final TargetPlatform targetPlatform, final File file ) { switch (targetPlatform) { case WINDOWS: return generateForWindows(file); case MACOS: return generateForMacOS(file); case LINUX_DEB: case LINUX_RPM: case UNIVERSAL_JAVA: default: throw new UnsupportedOperationException("Unsupported platform for self update installation execution!"); } } /** * Generates the required setup for macOS selfupdate. * * @param file The DMG image file to use for selfupdate * * @return The command line arguments to selfupdate with the given file */ private static String[] generateForMacOS(final File file) { final File tmpFolder = new File(TEMP_FOLDER, LYREBIRD_DL_FOLDER); final File installScriptTarget = new File(tmpFolder, "install_macos.sh"); try { final String installFileData = StreamUtils.copyToString( Lyrebird.class.getClassLoader().getResourceAsStream("scripts/install_macos.sh"), StandardCharsets.UTF_8 ); Files.write(installScriptTarget.toPath(), installFileData.getBytes(), TRUNCATE_EXISTING); //noinspection ResultOfMethodCallIgnored installScriptTarget.setExecutable(true); //noinspection ResultOfMethodCallIgnored installScriptTarget.setReadable(true); return new String[]{ "/bin/sh", installScriptTarget.toPath().toAbsolutePath().toString(), file.toPath().toAbsolutePath().toString() }; } catch (final IOException e) { throw new IllegalStateException("Could not copy install script to temporary folder!", e); } } /** * Generates the required command line arguments for Windows selfupdate. * * @param file The executable file to use for selfupdate (must be made via InnoSetup + JavaPackager) * * @return The required command line arguments for Windows selfupdate */ private static String[] generateForWindows(final File file) { return new String[]{ file.toPath().toAbsolutePath().toString(), "/SILENT", "/SP-", "/SUPPRESSMSGBOXES" }; } }
4,638
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
BinaryInstallationService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/update/selfupdate/BinaryInstallationService.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.update.selfupdate; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import moe.lyrebird.api.model.LyrebirdPackage; import moe.lyrebird.api.model.LyrebirdVersion; import moe.lyrebird.api.model.TargetPlatform; /** * This service, with the help of the {@link BinaryInstallationHelper}, generates the command line arguments for the * current platform to execute a selfupdate. * * @see BinaryInstallationHelper */ public final class BinaryInstallationService { private static final Logger LOG = LoggerFactory.getLogger(BinaryInstallationService.class); private static final String TEMP_FOLDER = System.getProperty("java.io.tmpdir"); private static final String LYREBIRD_DL_FOLDER = "lyrebird"; private BinaryInstallationService() { } /** * Determines the correct command line arguments for self-updating a given platform's executable to a given version. * * @param targetPlatform The platform on which the selfupdate shall be performed * @param lyrebirdVersion The version to which the selfupdate shall be performed * * @return The command line arguments for the selfupdate execution */ static String[] getInstallationCommandLine( final TargetPlatform targetPlatform, final LyrebirdVersion lyrebirdVersion ) { final Optional<LyrebirdPackage> acceptablePackage = findPackageForPlatform(lyrebirdVersion, targetPlatform); if (!acceptablePackage.isPresent()) { throw new IllegalStateException( "Could not find an acceptable package for platform " + targetPlatform + " in version : " + lyrebirdVersion ); } final LyrebirdPackage lyrebirdPackage = acceptablePackage.get(); final File downloadedBinary = downloadBinary(lyrebirdPackage.getPackageUrl()); return BinaryInstallationHelper.generateCommandLineForPlatformWithFile(targetPlatform, downloadedBinary); } /** * Finds the correct {@link LyrebirdPackage} for the given target platform. * * @param lyrebirdVersion The version to search a package from * @param targetPlatform The platform to search a package for * * @return The package if it was found, else {@link Optional#empty()}. */ private static Optional<LyrebirdPackage> findPackageForPlatform( final LyrebirdVersion lyrebirdVersion, final TargetPlatform targetPlatform ) { return lyrebirdVersion.getPackages() .stream() .filter(distributable -> distributable.getTargetPlatform().equals(targetPlatform)) .findAny(); } /** * Downloads a binary file locally to a temporary location that is platform dependent. * * @param binaryUrl The file to download's URL * * @return The downloaded file */ private static File downloadBinary(final URL binaryUrl) { final File targetFile = prepareTargetFile(binaryUrl); LOG.debug("Downloading {} to file {}", binaryUrl, targetFile); final long downloadedFileSize = downloadFileImpl(binaryUrl, targetFile); LOG.debug("Saved file {} to {} with size of {} bytes", binaryUrl, targetFile, downloadedFileSize); return targetFile; } /** * Prepares the location of the downloaded installation binary in the system's temporary folder. * * @param binaryUrl The URL of the binary (to match name mostly) * * @return The pre-made File reference to the location to which to download */ private static File prepareTargetFile(final URL binaryUrl) { final String[] binaryUrlSplit = binaryUrl.toExternalForm().split("/"); final String binaryFilename = binaryUrlSplit[binaryUrlSplit.length - 1]; final File tmpFolder = new File(TEMP_FOLDER, LYREBIRD_DL_FOLDER); if (tmpFolder.mkdirs()) { LOG.debug("Created temporary file download folder at {}", tmpFolder); } return new File(tmpFolder, binaryFilename); } /** * Downloads a file from a URL to a local location. * * @param binaryUrl The URL of the file to download * @param targetFile The location where to save the downloaded file * * @return The size of the downloaded file in bytes */ private static long downloadFileImpl(final URL binaryUrl, final File targetFile) { try (final InputStream binaryInputStream = binaryUrl.openStream()) { return Files.copy(binaryInputStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (final IOException e) { LOG.error("Could not download binary!", e); throw new IllegalStateException("Could not download binary! [" + binaryUrl.toExternalForm() + "]", e); } } }
5,921
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
Notification.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/notifications/Notification.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.notifications; import java.util.Objects; /** * Simple POJO to describe a notification. */ public final class Notification { private final String title; private final String text; /** * @param title The title to display for this notification * @param text The textual content to display in this notification */ public Notification(final String title, final String text) { this.title = title; this.text = text != null ? text : ""; } @Override public int hashCode() { return Objects.hash(getTitle(), getText()); } public String getTitle() { return title; } public String getText() { return text; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Notification)) { return false; } final Notification that = (Notification) o; return Objects.equals(getTitle(), that.getTitle()) && Objects.equals(getText(), that.getText()); } @Override public String toString() { return "Notification{" + "title='" + title + '\'' + ", text='" + text + '\'' + '}'; } }
2,116
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
NotificationSystemType.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/notifications/NotificationSystemType.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.notifications; import moe.lyrebird.model.notifications.system.AwtNotificationSystem; import moe.lyrebird.model.notifications.system.InternalNotificationSystem; import moe.lyrebird.model.notifications.system.NotificationSystem; /** * Simple convenience enumeration of the notification systems for more elegant calls to {@link NotificationService}. */ public enum NotificationSystemType { INTERNAL(InternalNotificationSystem.class), SYSTEM(AwtNotificationSystem.class); private final Class<? extends NotificationSystem> notificationSystemClass; NotificationSystemType(final Class<? extends NotificationSystem> notificationSystemClass) { this.notificationSystemClass = notificationSystemClass; } public Class<? extends NotificationSystem> getNotificationSystemClass() { return notificationSystemClass; } }
1,694
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
NotificationService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/notifications/NotificationService.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.notifications; import static moe.lyrebird.model.notifications.NotificationSystemType.INTERNAL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import javafx.stage.Stage; import moe.lyrebird.model.notifications.system.NotificationSystem; import moe.lyrebird.view.screens.root.RootScreenComponent; import moe.tristan.easyfxml.model.beanmanagement.StageManager; /** * This service is in charge of dispatching notification requests to the appropriate {@link NotificationSystem}. */ @Component public class NotificationService { private static final Logger LOG = LoggerFactory.getLogger(NotificationService.class); private final ApplicationContext context; private final StageManager stageManager; private final RootScreenComponent rootScreenComponent; @Autowired public NotificationService(ApplicationContext context, StageManager stageManager, RootScreenComponent rootScreenComponent) { this.context = context; this.stageManager = stageManager; this.rootScreenComponent = rootScreenComponent; } /** * Sends a notification to the user, automatically choosing the appropriate {@link NotificationSystem} depending on the current focus state of the main * window. * <p> * Will use the system-level system if the application's main window is not visible (that is, if it is minimized or hidden). * * @param notification The notification to display. */ public void sendNotification(final Notification notification) { LOG.debug("Requesting display of notification with smart display system type."); final Stage mainStage = stageManager.getSingle(rootScreenComponent).getOrElseThrow( () -> new IllegalStateException("Can not find main stage.") ); final boolean isVisible = mainStage.isShowing() && !mainStage.isIconified(); // TODO: re-enable native notifications once SystemTray issues are fixed final NotificationSystemType appropriateNotificationSystem = INTERNAL; LOG.debug("Determined that the appropriate notification system is {}", appropriateNotificationSystem); sendNotification(notification, appropriateNotificationSystem); } /** * Sends a notification to the user with a given {@link NotificationSystem}. * * @param notification The notification to send * @param notificationSystemType The notification system to use for that */ public void sendNotification(final Notification notification, final NotificationSystemType notificationSystemType) { LOG.debug("Requesting display of notification {} with type {}", notification, notificationSystemType); context.getBean(notificationSystemType.getNotificationSystemClass()) .displayNotification(notification); } }
3,844
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
InternalNotificationSystem.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/notifications/system/InternalNotificationSystem.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.notifications.system; import org.springframework.stereotype.Component; import moe.lyrebird.model.notifications.Notification; import moe.lyrebird.view.components.notifications.NotificationsController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javafx.beans.property.Property; import javafx.beans.property.SimpleObjectProperty; /** * JavaFX-based application-internal implementation of {@link NotificationSystem}. */ @Component public class InternalNotificationSystem implements NotificationSystem { private static final Logger LOG = LoggerFactory.getLogger(InternalNotificationSystem.class); private final Property<Notification> notificationProperty = new SimpleObjectProperty<>(null); /** * Sets-up the notification to display property for consumption by {@link NotificationsController}. * * @param notification the notification to display */ @Override public void displayNotification(final Notification notification) { LOG.debug("Queuing notification {} for display", notification); notificationProperty.setValue(notification); } /** * @return The notification currently requested for displaying */ public Property<Notification> notificationProperty() { return notificationProperty; } }
2,148
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
NotificationSystem.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/notifications/system/NotificationSystem.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.notifications.system; import moe.lyrebird.model.notifications.Notification; /** * Common interface for notification systems * * @see AwtNotificationSystem * @see InternalNotificationSystem */ public interface NotificationSystem { /** * Requests the display of a given notification. * * @param notification The notification to display. */ void displayNotification(final Notification notification); }
1,275
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
AwtNotificationSystem.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/notifications/system/AwtNotificationSystem.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.notifications.system; import org.springframework.stereotype.Component; import moe.lyrebird.model.notifications.Notification; import moe.lyrebird.model.systemtray.SystemTrayService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javafx.beans.property.Property; import java.awt.TrayIcon; /** * AWT-based native OS notification implementation of {@link NotificationSystem}. * * @see SystemTrayService */ @Component public class AwtNotificationSystem implements NotificationSystem { private static final Logger LOG = LoggerFactory.getLogger(AwtNotificationSystem.class); private final Property<TrayIcon> lyrebirdTrayIcon; public AwtNotificationSystem(final SystemTrayService trayService) { this.lyrebirdTrayIcon = trayService.trayIconProperty(); } /** * Displays a notification bound to the application's {@link TrayIcon}. * * @param notification the notification to display */ @Override public void displayNotification(final Notification notification) { LOG.debug("Sending AWT native notification : {}", notification); lyrebirdTrayIcon.getValue().displayMessage( notification.getTitle(), notification.getText(), TrayIcon.MessageType.NONE ); } }
2,143
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TwitterNotifications.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/notifications/format/TwitterNotifications.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.notifications.format; import moe.lyrebird.model.notifications.Notification; import twitter4j.Status; import twitter4j.User; /** * Helper methods for formatting notifications related to twitter events. */ public final class TwitterNotifications { private TwitterNotifications() { throw new AssertionError("Not instantiable."); } public static Notification fromMention(final Status mention) { final String title = mention.getUser().getName() + " mentioned you"; return new Notification(title, mention.getText()); } public static Notification fromFavorite(final User favoriter, final Status tweet) { final String title = favoriter.getName() + " liked one of your tweets:"; return new Notification(title, tweet.getText()); } public static Notification fromRetweet(final Status retweetingStatus) { final String title = retweetingStatus.getUser().getName() + " retweeted you"; return new Notification(title, retweetingStatus.getRetweetedStatus().getText()); } public static Notification fromQuotedTweet(final Status quotingStatus) { final String title = quotingStatus.getUser().getName() + " quoted you"; return new Notification( title, quotingStatus.getText() + "\n\n Quoted:\n" + quotingStatus.getQuotedStatus().getText() ); } public static Notification fromFollow(final User follower) { final String title = follower.getName() + " started following you!"; return new Notification(title, ""); } public static Notification fromUnfollow(final User unfollower) { final String title = unfollower.getName() + " unfollowed you :("; return new Notification(title, "unlucky... :("); } }
2,626
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
SessionManager.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/sessions/SessionManager.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.sessions; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.Cacheable; import org.springframework.context.ApplicationContext; import javafx.beans.property.Property; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import moe.lyrebird.model.twitter.twitter4j.TwitterHandler; import io.vavr.CheckedFunction1; import io.vavr.control.Try; import twitter4j.Twitter; import twitter4j.User; import twitter4j.auth.AccessToken; /** * The session manager is responsible for persisting the sessions in database and providing handles to them should * another component need access to them (i.e. the JavaFX controllers per example). */ public class SessionManager { private static final Logger LOG = LoggerFactory.getLogger(SessionManager.class); private final ApplicationContext context; private final SessionRepository sessionRepository; private final Set<Session> loadedSessions = new HashSet<>(); private final Property<Session> currentSession; private final Property<String> currentSessionUsername; private final Property<Boolean> isLoggedInProperty; public SessionManager(final ApplicationContext context, final SessionRepository sessionRepository) { this.context = context; this.sessionRepository = sessionRepository; this.currentSession = new SimpleObjectProperty<>(null); this.currentSessionUsername = new SimpleStringProperty("Logged out"); this.isLoggedInProperty = new SimpleBooleanProperty(false); this.currentSession.addListener( (ref, oldVal, newVal) -> { LOG.debug("Current session property changed from {} to {}", oldVal, newVal); currentSessionUsername.setValue(newVal.getUserScreenName()); isLoggedInProperty.setValue(true); } ); } public Property<Session> currentSessionProperty() { return currentSession; } public Property<Boolean> isLoggedInProperty() { return isLoggedInProperty; } public Property<String> currentSessionUsernameProperty() { return currentSessionUsername; } public boolean isCurrentUser(final User user) { return isCurrentUser(user.getId()); } @Cacheable("currentUserTest") public boolean isCurrentUser(final long userId) { return currentSessionProperty().getValue() .getTwitterUser() .map(User::getId) .map(curUserId -> curUserId == userId) .getOrElse(false); } public Try<Twitter> getCurrentTwitter() { return Try.of(() -> currentSession) .map(Property::getValue) .map(Session::getTwitterHandler) .map(TwitterHandler::getTwitter) .andThenTry(session -> LOG.trace( "Preparing request for user : {}", session.getScreenName() )); } public <T> Try<T> doWithCurrentTwitter(final CheckedFunction1<Twitter, T> action) { return getCurrentTwitter().mapTry(action); } /** * Loads all sessions stored in database. For each of them it will also create the respective {@link * TwitterHandler}. * * @return The number of new sessions loaded */ public long loadAllSessions() { final long initialSize = this.loadedSessions.size(); this.sessionRepository.findAll().forEach(this::loadSession); final long finalSize = this.loadedSessions.size(); final List<String> sessionUsernames = this.loadedSessions.stream() .map(Session::getUserId) .collect(Collectors.toList()); LOG.info( "Loaded {} Twitter sessions. Total loaded sessions so far is {}. Sessions : {}", finalSize - initialSize, finalSize, sessionUsernames ); return finalSize - initialSize; } private void loadSession(final Session session) { final TwitterHandler handler = this.context.getBean(TwitterHandler.class); handler.registerAccessToken(session.getAccessToken()); session.setTwitterHandler(handler); this.loadedSessions.add(session); LOG.debug("Setting current session to {}", session); this.currentSession.setValue(session); } public void addNewSession(final TwitterHandler twitterHandler) { final AccessToken accessToken = twitterHandler.getAccessToken(); final Session session = new Session( accessToken.getScreenName(), accessToken, twitterHandler ); this.loadSession(session); LOG.debug("Setting current session to {}", session); this.currentSession.setValue(session); this.saveAllSessions(); } /** * Saves all sessions. */ private void saveAllSessions() { this.loadedSessions.stream() .peek(session -> LOG.info("Saving Twitter session : {}", session)) .forEach(this.sessionRepository::save); LOG.debug("Saved all sessions !"); } }
6,490
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
SessionRepository.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/sessions/SessionRepository.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.sessions; import org.springframework.data.jpa.repository.JpaRepository; /** * Simple repository for {@link Session} elements mapped by twitter userId. */ public interface SessionRepository extends JpaRepository<Session, String> { }
1,076
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
Session.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/sessions/Session.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.sessions; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Transient; import moe.lyrebird.model.twitter.twitter4j.TwitterHandler; import io.vavr.control.Try; import twitter4j.User; import twitter4j.auth.AccessToken; /** * A session represents one {@link AccessToken} and the corresponding user id, which is the primary key. * <p> * It is serializable (and serialized) and can be retrieved to construct a {@link TwitterHandler instance}. * <p> * Unused warnings are disabled because Hibernate does use (and need) this class to have no-arg constructor and public getter/setter pairs for fields. */ @SuppressWarnings("unused") @Entity public class Session { @Id private String userId; @Column(length = 1000, name = "access_token") private AccessToken accessToken; @Transient private transient TwitterHandler twitterHandler; public Session() { } public Session(final String userId, final AccessToken accessToken, final TwitterHandler twitterHandler) { this.userId = userId; this.accessToken = accessToken; this.twitterHandler = twitterHandler; } public String getUserId() { return userId; } public void setUserId(final String userId) { this.userId = userId; } public String getUserScreenName() { if (accessToken == null) { return "<NOT_LOGGED_IN>"; } return accessToken.getScreenName(); } public AccessToken getAccessToken() { return accessToken; } public void setAccessToken(final AccessToken accessToken) { this.accessToken = accessToken; } public TwitterHandler getTwitterHandler() { return twitterHandler; } public void setTwitterHandler(final TwitterHandler twitterHandler) { this.twitterHandler = twitterHandler; } /** * @return the Twitter {@link User} associated with this Session. */ public Try<User> getTwitterUser() { final long self = accessToken.getUserId(); return Try.of(twitterHandler::getTwitter).mapTry(twitter -> twitter.showUser(self)); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Session)) { return false; } final Session session = (Session) o; return Objects.equals(userId, session.userId) && Objects.equals(accessToken, session.accessToken) && Objects.equals(twitterHandler, session.twitterHandler); } @Override public int hashCode() { return Objects.hash(userId, accessToken, twitterHandler); } @Override public String toString() { return "Session{" + "userId='" + userId + '\'' + ", accessToken=" + accessToken + '}'; } }
3,807
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
MainHook.java
/FileExtraction/Java_unseen/shatyuka_Killergram/app/src/main/java/com/shatyuka/killergram/MainHook.java
package com.shatyuka.killergram; import java.util.Arrays; import java.util.List; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodReplacement; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage; public class MainHook implements IXposedHookLoadPackage { public final static List<String> hookPackages = Arrays.asList( "org.telegram.messenger", "org.telegram.messenger.web", "org.telegram.messenger.beta", "nekox.messenger", "com.cool2645.nekolite", "org.telegram.plus", "com.iMe.android", "org.telegram.BifToGram", "ua.itaysonlab.messenger", "org.forkclient.messenger", "org.forkclient.messenger.beta", "org.aka.messenger", "ellipi.messenger", "org.nift4.catox", "it.owlgram.android"); @Override public void handleLoadPackage(final XC_LoadPackage.LoadPackageParam lpparam) { if (hookPackages.contains(lpparam.packageName)) { try { Class<?> messagesControllerClass = XposedHelpers.findClassIfExists("org.telegram.messenger.MessagesController", lpparam.classLoader); if (messagesControllerClass != null) { XposedBridge.hookAllMethods(messagesControllerClass, "getSponsoredMessages", XC_MethodReplacement.returnConstant(null)); XposedBridge.hookAllMethods(messagesControllerClass, "isChatNoForwards", XC_MethodReplacement.returnConstant(false)); } Class<?> chatUIActivityClass = XposedHelpers.findClassIfExists("org.telegram.ui.ChatActivity", lpparam.classLoader); if (chatUIActivityClass != null) { XposedBridge.hookAllMethods(chatUIActivityClass, "addSponsoredMessages", XC_MethodReplacement.returnConstant(null)); } Class<?> SharedConfigClass = XposedHelpers.findClassIfExists("org.telegram.messenger.SharedConfig", lpparam.classLoader); if (SharedConfigClass != null) { XposedBridge.hookAllMethods(SharedConfigClass, "getDevicePerformanceClass", XC_MethodReplacement.returnConstant(2)); } Class<?> UserConfigClass = XposedHelpers.findClassIfExists("org.telegram.messenger.UserConfig", lpparam.classLoader); if (UserConfigClass != null) { XposedBridge.hookAllMethods(UserConfigClass, "getMaxAccountCount", XC_MethodReplacement.returnConstant(999)); XposedBridge.hookAllMethods(UserConfigClass, "hasPremiumOnAccounts", XC_MethodReplacement.returnConstant(true)); } } catch (Throwable ignored) { } } } }
2,901
Java
.java
shatyuka/Killergram
557
48
25
2021-11-09T16:38:56Z
2024-03-27T12:38:34Z
INBT.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/API/src/main/java/com/lishid/orebfuscator/nms/INBT.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; public interface INBT { void reset(); void setInt(String tag, int value); void setLong(String tag, long value); void setByteArray(String tag, byte[] value); void setIntArray(String tag, int[] value); int getInt(String tag); long getLong(String tag); byte[] getByteArray(String tag); int[] getIntArray(String tag); void Read(DataInput stream) throws IOException; void Write(DataOutput stream) throws IOException; }
625
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
IBlockInfo.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/API/src/main/java/com/lishid/orebfuscator/nms/IBlockInfo.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms; public interface IBlockInfo { int getX(); int getY(); int getZ(); int getCombinedId(); }
168
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
INmsManager.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/API/src/main/java/com/lishid/orebfuscator/nms/INmsManager.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms; import com.lishid.orebfuscator.types.ConfigDefaults; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Player; import com.lishid.orebfuscator.types.BlockCoord; import java.util.Set; public interface INmsManager { ConfigDefaults getConfigDefaults(); Material[] getExtraTransparentBlocks(); void setMaxLoadedCacheFiles(int value); INBT createNBT(); IChunkCache createChunkCache(); void updateBlockTileEntity(BlockCoord blockCoord, Player player); void notifyBlockChange(World world, IBlockInfo blockInfo); int getBlockLightLevel(World world, int x, int y, int z); IBlockInfo getBlockInfo(World world, int x, int y, int z); int loadChunkAndGetBlockId(World world, int x, int y, int z); String getTextFromChatComponent(String json); boolean isHoe(Material item); boolean isSign(int combinedBlockId); boolean isAir(int combinedBlockId); boolean isTileEntity(int combinedBlockId); int getCaveAirBlockId(); int getBitsPerBlock(); boolean canApplyPhysics(Material blockMaterial); Set<Integer> getMaterialIds(Material material); boolean sendBlockChange(Player player, Location blockLocation); }
1,291
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
IChunkCache.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/API/src/main/java/com/lishid/orebfuscator/nms/IChunkCache.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; public interface IChunkCache { DataInputStream getInputStream(File folder, int x, int z); DataOutputStream getOutputStream(File folder, int x, int z); void closeCacheFiles(); }
357
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkCoord.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/API/src/main/java/com/lishid/orebfuscator/types/ChunkCoord.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.types; public class ChunkCoord { public int x; public int z; public ChunkCoord(int x, int z) { this.x = x; this.z = z; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof ChunkCoord)) { return false; } ChunkCoord object = (ChunkCoord) other; return this.x == object.x && this.z == object.z; } @Override public int hashCode() { return this.x ^ this.z; } @Override public String toString() { return this.x + " " + this.z; } }
576
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
BlockCoord.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/API/src/main/java/com/lishid/orebfuscator/types/BlockCoord.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.types; public class BlockCoord { public int x; public int y; public int z; public BlockCoord(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof BlockCoord)) { return false; } BlockCoord object = (BlockCoord) other; return this.x == object.x && this.y == object.y && this.z == object.z; } @Override public int hashCode() { return this.x ^ this.y ^ this.z; } @Override public String toString() { return this.x + " " + this.y + " " + this.z; } }
658
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ConfigDefaults.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/API/src/main/java/com/lishid/orebfuscator/types/ConfigDefaults.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.types; public class ConfigDefaults { public int[] defaultProximityHiderBlockIds; public int[] defaultDarknessBlockIds; public int defaultMode1BlockId; public int defaultProximityHiderSpecialBlockId; public int[] endWorldRandomBlockIds; public int[] endWorldObfuscateBlockIds; public int endWorldMode1BlockId; public int[] endWorldRequiredObfuscateBlockIds; public int[] netherWorldRandomBlockIds; public int[] netherWorldObfuscateBlockIds; public int netherWorldMode1BlockId; public int[] netherWorldRequiredObfuscateBlockIds; public int[] normalWorldRandomBlockIds; public int[] normalWorldObfuscateBlockIds; public int normalWorldMode1BlockId; public int[] normalWorldRequiredObfuscateBlockIds; }
835
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NBT.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_13_R2/src/main/java/com/lishid/orebfuscator/nms/v1_13_R2/NBT.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_13_R2; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.IOException; import net.minecraft.server.v1_13_R2.NBTCompressedStreamTools; import net.minecraft.server.v1_13_R2.NBTTagCompound; import com.lishid.orebfuscator.nms.INBT; public class NBT implements INBT { NBTTagCompound nbt = new NBTTagCompound(); public void reset() { nbt = new NBTTagCompound(); } public void setInt(String tag, int value) { nbt.setInt(tag, value); } public void setLong(String tag, long value) { nbt.setLong(tag, value); } public void setByteArray(String tag, byte[] value) { nbt.setByteArray(tag, value); } public void setIntArray(String tag, int[] value) { nbt.setIntArray(tag, value); } public int getInt(String tag) { return nbt.getInt(tag); } public long getLong(String tag) { return nbt.getLong(tag); } public byte[] getByteArray(String tag) { return nbt.getByteArray(tag); } public int[] getIntArray(String tag) { return nbt.getIntArray(tag); } public void Read(DataInput stream) throws IOException { nbt = NBTCompressedStreamTools.a((DataInputStream) stream); } public void Write(DataOutput stream) throws IOException { NBTCompressedStreamTools.a(nbt, stream); } }
1,489
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NmsManager.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_13_R2/src/main/java/com/lishid/orebfuscator/nms/v1_13_R2/NmsManager.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_13_R2; import com.lishid.orebfuscator.types.ConfigDefaults; import net.minecraft.server.v1_13_R2.*; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.craftbukkit.v1_13_R2.CraftWorld; import org.bukkit.craftbukkit.v1_13_R2.block.CraftBlock; import org.bukkit.craftbukkit.v1_13_R2.block.data.CraftBlockData; import org.bukkit.craftbukkit.v1_13_R2.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_13_R2.util.CraftChatMessage; import org.bukkit.entity.Player; import com.lishid.orebfuscator.nms.IBlockInfo; import com.lishid.orebfuscator.nms.IChunkCache; import com.lishid.orebfuscator.nms.INBT; import com.lishid.orebfuscator.nms.INmsManager; import com.lishid.orebfuscator.types.BlockCoord; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class NmsManager implements INmsManager { private static final int BITS_PER_BLOCK = 14; private int BLOCK_ID_CAVE_AIR; private Set<Integer> BLOCK_ID_AIRS; private Set<Integer> BLOCK_ID_SIGNS; private ConfigDefaults configDefaults; private int maxLoadedCacheFiles; private Material[] extraTransparentBlocks; private HashMap<Material, Set<Integer>> materialIds; public NmsManager() { initBlockIds(); this.BLOCK_ID_CAVE_AIR = getMaterialIds(Material.CAVE_AIR).iterator().next(); this.BLOCK_ID_AIRS = convertMaterialsToSet(new Material[] { Material.AIR, Material.CAVE_AIR, Material.VOID_AIR }); this.BLOCK_ID_SIGNS = convertMaterialsToSet(new Material[] { Material.SIGN, Material.WALL_SIGN }); this.configDefaults = new ConfigDefaults(); // Default World this.configDefaults.defaultProximityHiderBlockIds = convertMaterialsToIds(new Material[] { Material.DISPENSER, Material.SPAWNER, Material.CHEST, Material.HOPPER, Material.CRAFTING_TABLE, Material.FURNACE, Material.ENCHANTING_TABLE, Material.EMERALD_ORE, Material.ENDER_CHEST, Material.ANVIL, Material.CHIPPED_ANVIL, Material.DAMAGED_ANVIL, Material.TRAPPED_CHEST, Material.DIAMOND_ORE }); this.configDefaults.defaultDarknessBlockIds = convertMaterialsToIds(new Material[] { Material.SPAWNER, Material.CHEST }); this.configDefaults.defaultMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.defaultProximityHiderSpecialBlockId = getMaterialIds(Material.STONE).iterator().next(); // The End this.configDefaults.endWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.BEDROCK, Material.OBSIDIAN, Material.END_STONE, Material.PURPUR_BLOCK, Material.END_STONE_BRICKS }); this.configDefaults.endWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.END_STONE }); this.configDefaults.endWorldMode1BlockId = getMaterialIds(Material.END_STONE).iterator().next(); this.configDefaults.endWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.END_STONE }); // Nether World this.configDefaults.netherWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.GRAVEL, Material.NETHERRACK, Material.SOUL_SAND, Material.NETHER_BRICKS, Material.NETHER_QUARTZ_ORE }); this.configDefaults.netherWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK, Material.NETHER_QUARTZ_ORE }); this.configDefaults.netherWorldMode1BlockId = getMaterialIds(Material.NETHERRACK).iterator().next(); this.configDefaults.netherWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK }); // Normal World this.configDefaults.normalWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.STONE, Material.COBBLESTONE, Material.OAK_PLANKS, Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.TNT, Material.MOSSY_COBBLESTONE, Material.OBSIDIAN, Material.DIAMOND_ORE, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.CHEST, Material.DIAMOND_ORE, Material.ENDER_CHEST, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.normalWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.STONE }); // Extra transparent blocks this.extraTransparentBlocks = new Material[] { Material.ACACIA_DOOR, Material.ACACIA_FENCE, Material.ACACIA_FENCE_GATE, Material.ACACIA_LEAVES, Material.ACACIA_PRESSURE_PLATE, Material.ACACIA_SLAB, Material.ACACIA_STAIRS, Material.ACACIA_TRAPDOOR, Material.ANVIL, Material.BEACON, Material.BIRCH_DOOR, Material.BIRCH_FENCE, Material.BIRCH_FENCE_GATE, Material.BIRCH_LEAVES, Material.BIRCH_PRESSURE_PLATE, Material.BIRCH_SLAB, Material.BIRCH_STAIRS, Material.BIRCH_TRAPDOOR, Material.BLACK_BANNER, Material.BLACK_BED, Material.BLACK_STAINED_GLASS, Material.BLACK_STAINED_GLASS_PANE, Material.BLACK_WALL_BANNER, Material.BLUE_BANNER, Material.BLUE_BED, Material.BLUE_ICE, Material.BLUE_STAINED_GLASS, Material.BLUE_STAINED_GLASS_PANE, Material.BLUE_WALL_BANNER, Material.BREWING_STAND, Material.BRICK_SLAB, Material.BRICK_STAIRS, Material.BRAIN_CORAL, Material.BRAIN_CORAL_FAN, Material.BRAIN_CORAL_WALL_FAN, Material.BROWN_BANNER, Material.BROWN_BED, Material.BROWN_STAINED_GLASS, Material.BROWN_STAINED_GLASS_PANE, Material.BROWN_WALL_BANNER, Material.BUBBLE_COLUMN, Material.BUBBLE_CORAL, Material.BUBBLE_CORAL_FAN, Material.BUBBLE_CORAL_WALL_FAN, Material.CACTUS, Material.CAKE, Material.CAULDRON, Material.CHIPPED_ANVIL, Material.COBBLESTONE_SLAB, Material.COBBLESTONE_STAIRS, Material.COBBLESTONE_WALL, Material.COBWEB, Material.CONDUIT, Material.CYAN_BANNER, Material.CYAN_BED, Material.CYAN_STAINED_GLASS, Material.CYAN_STAINED_GLASS_PANE, Material.CYAN_WALL_BANNER, Material.DAMAGED_ANVIL, Material.DARK_OAK_DOOR, Material.DARK_OAK_FENCE, Material.DARK_OAK_FENCE_GATE, Material.DARK_OAK_LEAVES, Material.DARK_OAK_PRESSURE_PLATE, Material.DARK_OAK_SLAB, Material.DARK_OAK_STAIRS, Material.DARK_OAK_TRAPDOOR, Material.DARK_PRISMARINE_SLAB, Material.DARK_PRISMARINE_STAIRS, Material.DAYLIGHT_DETECTOR, Material.DEAD_BRAIN_CORAL, Material.DEAD_BRAIN_CORAL_FAN, Material.DEAD_BRAIN_CORAL_WALL_FAN, Material.DEAD_BUBBLE_CORAL, Material.DEAD_BUBBLE_CORAL_FAN, Material.DEAD_BUBBLE_CORAL_WALL_FAN, Material.DEAD_FIRE_CORAL, Material.DEAD_FIRE_CORAL_FAN, Material.DEAD_FIRE_CORAL_WALL_FAN, Material.DEAD_HORN_CORAL, Material.DEAD_HORN_CORAL_FAN, Material.DEAD_HORN_CORAL_WALL_FAN, Material.DEAD_TUBE_CORAL, Material.DEAD_TUBE_CORAL_FAN, Material.DEAD_TUBE_CORAL_WALL_FAN, Material.DRAGON_EGG, Material.FARMLAND, Material.FIRE_CORAL, Material.FIRE_CORAL_FAN, Material.FIRE_CORAL_WALL_FAN, Material.FROSTED_ICE, Material.GLASS, Material.GLASS_PANE, Material.GRAY_BANNER, Material.GRAY_BED, Material.GRAY_STAINED_GLASS, Material.GRAY_STAINED_GLASS_PANE, Material.GRAY_WALL_BANNER, Material.GREEN_BANNER, Material.GREEN_BED, Material.GREEN_STAINED_GLASS, Material.GREEN_STAINED_GLASS_PANE, Material.GREEN_WALL_BANNER, Material.HEAVY_WEIGHTED_PRESSURE_PLATE, Material.HOPPER, Material.HORN_CORAL, Material.HORN_CORAL_FAN, Material.HORN_CORAL_WALL_FAN, Material.ICE, Material.IRON_BARS, Material.IRON_DOOR, Material.IRON_TRAPDOOR, Material.JUNGLE_DOOR, Material.JUNGLE_FENCE, Material.JUNGLE_FENCE_GATE, Material.JUNGLE_LEAVES, Material.JUNGLE_PRESSURE_PLATE, Material.JUNGLE_SLAB, Material.JUNGLE_STAIRS, Material.JUNGLE_TRAPDOOR, Material.KELP, Material.KELP_PLANT, Material.LIGHT_BLUE_BANNER, Material.LIGHT_BLUE_BED, Material.LIGHT_BLUE_STAINED_GLASS, Material.LIGHT_BLUE_STAINED_GLASS_PANE, Material.LIGHT_BLUE_WALL_BANNER, Material.LIGHT_GRAY_BANNER, Material.LIGHT_GRAY_BED, Material.LIGHT_GRAY_STAINED_GLASS, Material.LIGHT_GRAY_STAINED_GLASS_PANE, Material.LIGHT_GRAY_WALL_BANNER, Material.LIGHT_WEIGHTED_PRESSURE_PLATE, Material.LIME_BANNER, Material.LIME_BED, Material.LIME_STAINED_GLASS, Material.LIME_STAINED_GLASS_PANE, Material.LIME_WALL_BANNER, Material.MAGENTA_BANNER, Material.MAGENTA_BED, Material.MAGENTA_STAINED_GLASS, Material.MAGENTA_STAINED_GLASS_PANE, Material.MAGENTA_WALL_BANNER, Material.MOSSY_COBBLESTONE_WALL, Material.MOVING_PISTON, Material.NETHER_BRICK_FENCE, Material.NETHER_BRICK_SLAB, Material.NETHER_BRICK_STAIRS, Material.OAK_DOOR, Material.OAK_FENCE, Material.OAK_FENCE_GATE, Material.OAK_LEAVES, Material.OAK_PRESSURE_PLATE, Material.OAK_SLAB, Material.OAK_STAIRS, Material.OAK_TRAPDOOR, Material.ORANGE_BANNER, Material.ORANGE_BED, Material.ORANGE_STAINED_GLASS, Material.ORANGE_STAINED_GLASS_PANE, Material.ORANGE_WALL_BANNER, Material.PACKED_ICE, Material.PETRIFIED_OAK_SLAB, Material.PINK_BANNER, Material.PINK_BED, Material.PINK_STAINED_GLASS, Material.PINK_STAINED_GLASS_PANE, Material.PINK_WALL_BANNER, Material.PISTON, Material.PISTON_HEAD, Material.PRISMARINE_BRICK_SLAB, Material.PRISMARINE_BRICK_STAIRS, Material.PRISMARINE_SLAB, Material.PRISMARINE_STAIRS, Material.PURPLE_BANNER, Material.PURPLE_BED, Material.PURPLE_STAINED_GLASS, Material.PURPLE_STAINED_GLASS_PANE, Material.PURPLE_WALL_BANNER, Material.PURPUR_SLAB, Material.PURPUR_STAIRS, Material.QUARTZ_SLAB, Material.QUARTZ_STAIRS, Material.RED_BANNER, Material.RED_BED, Material.RED_SANDSTONE_SLAB, Material.RED_SANDSTONE_STAIRS, Material.RED_STAINED_GLASS, Material.RED_STAINED_GLASS_PANE, Material.RED_WALL_BANNER, Material.SANDSTONE_SLAB, Material.SANDSTONE_STAIRS, Material.SEAGRASS, Material.SEA_PICKLE, Material.SIGN, Material.SLIME_BLOCK, Material.SPAWNER, Material.SPRUCE_DOOR, Material.SPRUCE_FENCE, Material.SPRUCE_FENCE_GATE, Material.SPRUCE_LEAVES, Material.SPRUCE_PRESSURE_PLATE, Material.SPRUCE_SLAB, Material.SPRUCE_STAIRS, Material.SPRUCE_TRAPDOOR, Material.STICKY_PISTON, Material.STONE_BRICK_SLAB, Material.STONE_BRICK_STAIRS, Material.STONE_PRESSURE_PLATE, Material.STONE_SLAB, Material.TALL_SEAGRASS, Material.TUBE_CORAL, Material.TUBE_CORAL_FAN, Material.TUBE_CORAL_WALL_FAN, Material.TURTLE_EGG, Material.WALL_SIGN, Material.WATER, Material.WHITE_BANNER, Material.WHITE_BED, Material.WHITE_STAINED_GLASS, Material.WHITE_STAINED_GLASS_PANE, Material.WHITE_WALL_BANNER, Material.YELLOW_BANNER, Material.YELLOW_BED, Material.YELLOW_STAINED_GLASS, Material.YELLOW_STAINED_GLASS_PANE, Material.YELLOW_WALL_BANNER }; } private void initBlockIds() { this.materialIds = new HashMap<>(); Block.REGISTRY_ID.iterator().forEachRemaining(blockData -> { Material material = CraftBlockData.fromData(blockData).getMaterial(); if(material.isBlock()) { int materialId = Block.REGISTRY_ID.getId(blockData); Set<Integer> ids = this.materialIds.get(material); if (ids == null) { this.materialIds.put(material, ids = new HashSet<>()); } ids.add(materialId); } }); } public Material[] getExtraTransparentBlocks() { return this.extraTransparentBlocks; } public ConfigDefaults getConfigDefaults() { return this.configDefaults; } public void setMaxLoadedCacheFiles(int value) { this.maxLoadedCacheFiles = value; } public INBT createNBT() { return new NBT(); } public IChunkCache createChunkCache() { return new ChunkCache(this.maxLoadedCacheFiles); } public void updateBlockTileEntity(BlockCoord blockCoord, Player player) { CraftWorld world = (CraftWorld)player.getWorld(); // 1.13.2 has made this quite a bit different in later builds. TileEntity tileEntity = null; try { Method getTileEntityAt = world.getClass().getMethod("getTileEntityAt", int.class, int.class, int.class); tileEntity = (TileEntity) getTileEntityAt.invoke(world, blockCoord.x, blockCoord.y, blockCoord.z); } catch (NoSuchMethodException nsme) { tileEntity = world.getHandle().getTileEntity(new BlockPosition(blockCoord.x, blockCoord.y, blockCoord.z)); } catch (Exception e) { return; } if (tileEntity == null) { return; } Packet<?> packet = tileEntity.getUpdatePacket(); if (packet != null) { CraftPlayer player2 = (CraftPlayer)player; player2.getHandle().playerConnection.sendPacket(packet); } } public void notifyBlockChange(World world, IBlockInfo blockInfo) { BlockPosition blockPosition = new BlockPosition(blockInfo.getX(), blockInfo.getY(), blockInfo.getZ()); IBlockData blockData = ((BlockInfo)blockInfo).getBlockData(); ((CraftWorld)world).getHandle().notify(blockPosition, blockData, blockData, 0); } public int getBlockLightLevel(World world, int x, int y, int z) { return ((CraftWorld)world).getHandle().getLightLevel(new BlockPosition(x, y, z)); } public IBlockInfo getBlockInfo(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, false); return blockData != null ? new BlockInfo(x, y, z, blockData) : null; } public int loadChunkAndGetBlockId(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, true); return blockData != null ? Block.getCombinedId(blockData): -1; } public String getTextFromChatComponent(String json) { IChatBaseComponent component = IChatBaseComponent.ChatSerializer.a(json); return CraftChatMessage.fromComponent(component); } public boolean isHoe(Material item) { return item == Material.WOODEN_HOE || item == Material.IRON_HOE || item == Material.GOLDEN_HOE || item == Material.DIAMOND_HOE; } public boolean isSign(int combinedBlockId) { return BLOCK_ID_SIGNS.contains(combinedBlockId); } public boolean isAir(int combinedBlockId) { return BLOCK_ID_AIRS.contains(combinedBlockId); } public boolean isTileEntity(int combinedBlockId) { return Block.getByCombinedId(combinedBlockId).getBlock().isTileEntity(); } public int getCaveAirBlockId() { return BLOCK_ID_CAVE_AIR; } public int getBitsPerBlock() { return BITS_PER_BLOCK; } public boolean canApplyPhysics(Material blockMaterial) { return blockMaterial == Material.AIR || blockMaterial == Material.CAVE_AIR || blockMaterial == Material.VOID_AIR || blockMaterial == Material.FIRE || blockMaterial == Material.WATER || blockMaterial == Material.LAVA; } public Set<Integer> getMaterialIds(Material material) { return this.materialIds.get(material); } public boolean sendBlockChange(Player player, Location blockLocation) { IBlockData blockData = getBlockData(blockLocation.getWorld(), blockLocation.getBlockX(), blockLocation.getBlockY(), blockLocation.getBlockZ(), false); if(blockData == null) return false; CraftBlockData craftBlockData = CraftBlockData.fromData(blockData); player.sendBlockChange(blockLocation, craftBlockData); return true; } private static IBlockData getBlockData(World world, int x, int y, int z, boolean loadChunk) { int chunkX = x >> 4; int chunkZ = z >> 4; WorldServer worldServer = ((CraftWorld)world).getHandle(); // like in ChunkCache, NMS change without R increment. ChunkProviderServer chunkProviderServer = null; try { Method getChunkProviderServer = worldServer.getClass().getDeclaredMethod("getChunkProviderServer"); chunkProviderServer = (ChunkProviderServer) getChunkProviderServer.invoke(worldServer); } catch (NoSuchMethodException nmfe) { try { Method getChunkProvider = worldServer.getClass().getDeclaredMethod("getChunkProvider"); chunkProviderServer = (ChunkProviderServer) getChunkProvider.invoke(worldServer); } catch (NoSuchMethodException nsme) { return null; // oops } catch (Exception e) { return null; } } catch (Exception e) { return null; } if(!loadChunk && !chunkProviderServer.isLoaded(chunkX, chunkZ)) return null; Chunk chunk = chunkProviderServer.getChunkAt(chunkX, chunkZ, true, true); return chunk != null ? chunk.getBlockData(x, y, z) : null; } private Set<Integer> convertMaterialsToSet(Material[] materials) { Set<Integer> ids = new HashSet<>(); for(Material material : materials) { ids.addAll(getMaterialIds(material)); } return ids; } private int[] convertMaterialsToIds(Material[] materials) { Set<Integer> ids = convertMaterialsToSet(materials); int[] result = new int[ids.size()]; int index = 0; for(int id : ids) { result[index++] = id; } return result; } }
17,549
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkCache.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_13_R2/src/main/java/com/lishid/orebfuscator/nms/v1_13_R2/ChunkCache.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_13_R2; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.lang.reflect.Method; import java.util.HashMap; import net.minecraft.server.v1_13_R2.RegionFile; import com.lishid.orebfuscator.nms.IChunkCache; public class ChunkCache implements IChunkCache { private static final HashMap<File, RegionFile> cachedRegionFiles = new HashMap<File, RegionFile>(); private int maxLoadedCacheFiles; public ChunkCache(int maxLoadedCacheFiles) { this.maxLoadedCacheFiles = maxLoadedCacheFiles; } public DataInputStream getInputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.a(x & 0x1F, z & 0x1F); } public DataOutputStream getOutputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.c(x & 0x1F, z & 0x1F); } public void closeCacheFiles() { closeCacheFilesInternal(); } private synchronized RegionFile getRegionFile(File folder, int x, int z) { File path = new File(folder, "region"); File file = new File(path, "r." + (x >> 5) + "." + (z >> 5) + ".mcr"); try { RegionFile regionFile = cachedRegionFiles.get(file); if (regionFile != null) { return regionFile; } if (!path.exists()) { path.mkdirs(); } if (cachedRegionFiles.size() >= this.maxLoadedCacheFiles) { closeCacheFiles(); } regionFile = new RegionFile(file); cachedRegionFiles.put(file, regionFile); return regionFile; } catch (Exception e) { try { file.delete(); } catch (Exception e2) { } } return null; } private synchronized void closeCacheFilesInternal() { for (RegionFile regionFile : cachedRegionFiles.values()) { try { if (regionFile != null) { // This lovely piece of work is due to an NMS change in Spigot 1.13.2 without an R increase. try { Method c = regionFile.getClass().getDeclaredMethod("c"); c.invoke(regionFile); } catch (NoSuchMethodException nsme) { try { Method close = regionFile.getClass().getDeclaredMethod("close"); close.invoke(regionFile); } catch (NoSuchMethodException nsme2) { } } } } catch (Exception e) { e.printStackTrace(); } } cachedRegionFiles.clear(); } }
2,943
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
BlockInfo.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_13_R2/src/main/java/com/lishid/orebfuscator/nms/v1_13_R2/BlockInfo.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_13_R2; import net.minecraft.server.v1_13_R2.Block; import net.minecraft.server.v1_13_R2.IBlockData; import com.lishid.orebfuscator.nms.IBlockInfo; public class BlockInfo implements IBlockInfo { private int x; private int y; private int z; private IBlockData blockData; public BlockInfo(int x, int y, int z, IBlockData blockData) { this.x = x; this.y = y; this.z = z; this.blockData = blockData; } public int getX() { return this.x; } public int getY() { return this.y; } public int getZ() { return this.z; } public int getCombinedId() { return Block.getCombinedId(this.blockData); } public IBlockData getBlockData() { return this.blockData; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof BlockInfo)) { return false; } BlockInfo object = (BlockInfo) other; return this.x == object.x && this.y == object.y && this.z == object.z; } @Override public int hashCode() { return this.x ^ this.y ^ this.z; } @Override public String toString() { return this.x + " " + this.y + " " + this.z; } }
1,182
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NBT.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_13_R1/src/main/java/com/lishid/orebfuscator/nms/v1_13_R1/NBT.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_13_R1; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.IOException; import net.minecraft.server.v1_13_R1.NBTCompressedStreamTools; import net.minecraft.server.v1_13_R1.NBTTagCompound; import com.lishid.orebfuscator.nms.INBT; public class NBT implements INBT { NBTTagCompound nbt = new NBTTagCompound(); public void reset() { nbt = new NBTTagCompound(); } public void setInt(String tag, int value) { nbt.setInt(tag, value); } public void setLong(String tag, long value) { nbt.setLong(tag, value); } public void setByteArray(String tag, byte[] value) { nbt.setByteArray(tag, value); } public void setIntArray(String tag, int[] value) { nbt.setIntArray(tag, value); } public int getInt(String tag) { return nbt.getInt(tag); } public long getLong(String tag) { return nbt.getLong(tag); } public byte[] getByteArray(String tag) { return nbt.getByteArray(tag); } public int[] getIntArray(String tag) { return nbt.getIntArray(tag); } public void Read(DataInput stream) throws IOException { nbt = NBTCompressedStreamTools.a((DataInputStream) stream); } public void Write(DataOutput stream) throws IOException { NBTCompressedStreamTools.a(nbt, stream); } }
1,489
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NmsManager.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_13_R1/src/main/java/com/lishid/orebfuscator/nms/v1_13_R1/NmsManager.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_13_R1; import com.lishid.orebfuscator.types.ConfigDefaults; import net.minecraft.server.v1_13_R1.Block; import net.minecraft.server.v1_13_R1.BlockPosition; import net.minecraft.server.v1_13_R1.Chunk; import net.minecraft.server.v1_13_R1.ChunkProviderServer; import net.minecraft.server.v1_13_R1.IBlockData; import net.minecraft.server.v1_13_R1.IChatBaseComponent; import net.minecraft.server.v1_13_R1.Packet; import net.minecraft.server.v1_13_R1.TileEntity; import net.minecraft.server.v1_13_R1.WorldServer; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.craftbukkit.v1_13_R1.CraftWorld; import org.bukkit.craftbukkit.v1_13_R1.block.data.CraftBlockData; import org.bukkit.craftbukkit.v1_13_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_13_R1.util.CraftChatMessage; import org.bukkit.entity.Player; import com.lishid.orebfuscator.nms.IBlockInfo; import com.lishid.orebfuscator.nms.IChunkCache; import com.lishid.orebfuscator.nms.INBT; import com.lishid.orebfuscator.nms.INmsManager; import com.lishid.orebfuscator.types.BlockCoord; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class NmsManager implements INmsManager { private static final int BITS_PER_BLOCK = 14; private int BLOCK_ID_CAVE_AIR; private Set<Integer> BLOCK_ID_AIRS; private Set<Integer> BLOCK_ID_SIGNS; private ConfigDefaults configDefaults; private Material[] extraTransparentBlocks; private int maxLoadedCacheFiles; private HashMap<Material, Set<Integer>> materialIds; public NmsManager() { initBlockIds(); this.BLOCK_ID_CAVE_AIR = getMaterialIds(Material.CAVE_AIR).iterator().next(); this.BLOCK_ID_AIRS = convertMaterialsToSet(new Material[] { Material.AIR, Material.CAVE_AIR, Material.VOID_AIR }); this.BLOCK_ID_SIGNS = convertMaterialsToSet(new Material[] { Material.SIGN, Material.WALL_SIGN }); this.configDefaults = new ConfigDefaults(); // Default World this.configDefaults.defaultProximityHiderBlockIds = convertMaterialsToIds(new Material[] { Material.DISPENSER, Material.SPAWNER, Material.CHEST, Material.HOPPER, Material.CRAFTING_TABLE, Material.FURNACE, Material.ENCHANTING_TABLE, Material.EMERALD_ORE, Material.ENDER_CHEST, Material.ANVIL, Material.CHIPPED_ANVIL, Material.DAMAGED_ANVIL, Material.TRAPPED_CHEST, Material.DIAMOND_ORE }); this.configDefaults.defaultDarknessBlockIds = convertMaterialsToIds(new Material[] { Material.SPAWNER, Material.CHEST }); this.configDefaults.defaultMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.defaultProximityHiderSpecialBlockId = getMaterialIds(Material.STONE).iterator().next(); // The End this.configDefaults.endWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.BEDROCK, Material.OBSIDIAN, Material.END_STONE, Material.PURPUR_BLOCK, Material.END_STONE_BRICKS }); this.configDefaults.endWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.END_STONE }); this.configDefaults.endWorldMode1BlockId = getMaterialIds(Material.END_STONE).iterator().next(); this.configDefaults.endWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.END_STONE }); // Nether World this.configDefaults.netherWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.GRAVEL, Material.NETHERRACK, Material.SOUL_SAND, Material.NETHER_BRICKS, Material.NETHER_QUARTZ_ORE }); this.configDefaults.netherWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK, Material.NETHER_QUARTZ_ORE }); this.configDefaults.netherWorldMode1BlockId = getMaterialIds(Material.NETHERRACK).iterator().next(); this.configDefaults.netherWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK }); // Normal World this.configDefaults.normalWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.STONE, Material.COBBLESTONE, Material.OAK_PLANKS, Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.TNT, Material.MOSSY_COBBLESTONE, Material.OBSIDIAN, Material.DIAMOND_ORE, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.CHEST, Material.DIAMOND_ORE, Material.ENDER_CHEST, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.normalWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.STONE }); // Extra transparent blocks this.extraTransparentBlocks = new Material[] { Material.ACACIA_DOOR, Material.ACACIA_FENCE, Material.ACACIA_FENCE_GATE, Material.ACACIA_LEAVES, Material.ACACIA_PRESSURE_PLATE, Material.ACACIA_SLAB, Material.ACACIA_STAIRS, Material.ACACIA_TRAPDOOR, Material.ANVIL, Material.BEACON, Material.BIRCH_DOOR, Material.BIRCH_FENCE, Material.BIRCH_FENCE_GATE, Material.BIRCH_LEAVES, Material.BIRCH_PRESSURE_PLATE, Material.BIRCH_SLAB, Material.BIRCH_STAIRS, Material.BIRCH_TRAPDOOR, Material.BLACK_BANNER, Material.BLACK_BED, Material.BLACK_STAINED_GLASS, Material.BLACK_STAINED_GLASS_PANE, Material.BLACK_WALL_BANNER, Material.BLUE_BANNER, Material.BLUE_BED, Material.BLUE_ICE, Material.BLUE_STAINED_GLASS, Material.BLUE_STAINED_GLASS_PANE, Material.BLUE_WALL_BANNER, Material.BREWING_STAND, Material.BRICK_SLAB, Material.BRICK_STAIRS, Material.BRAIN_CORAL, Material.BRAIN_CORAL_FAN, Material.BRAIN_CORAL_WALL_FAN, Material.BROWN_BANNER, Material.BROWN_BED, Material.BROWN_STAINED_GLASS, Material.BROWN_STAINED_GLASS_PANE, Material.BROWN_WALL_BANNER, Material.BUBBLE_COLUMN, Material.BUBBLE_CORAL, Material.BUBBLE_CORAL_FAN, Material.BUBBLE_CORAL_WALL_FAN, Material.CACTUS, Material.CAKE, Material.CAULDRON, Material.CHIPPED_ANVIL, Material.COBBLESTONE_SLAB, Material.COBBLESTONE_STAIRS, Material.COBBLESTONE_WALL, Material.COBWEB, Material.CONDUIT, Material.CYAN_BANNER, Material.CYAN_BED, Material.CYAN_STAINED_GLASS, Material.CYAN_STAINED_GLASS_PANE, Material.CYAN_WALL_BANNER, Material.DAMAGED_ANVIL, Material.DARK_OAK_DOOR, Material.DARK_OAK_FENCE, Material.DARK_OAK_FENCE_GATE, Material.DARK_OAK_LEAVES, Material.DARK_OAK_PRESSURE_PLATE, Material.DARK_OAK_SLAB, Material.DARK_OAK_STAIRS, Material.DARK_OAK_TRAPDOOR, Material.DARK_PRISMARINE_SLAB, Material.DARK_PRISMARINE_STAIRS, Material.DAYLIGHT_DETECTOR, Material.DEAD_BRAIN_CORAL_FAN, Material.DEAD_BRAIN_CORAL_WALL_FAN, Material.DEAD_BUBBLE_CORAL_FAN, Material.DEAD_BUBBLE_CORAL_WALL_FAN, Material.DEAD_FIRE_CORAL_FAN, Material.DEAD_FIRE_CORAL_WALL_FAN, Material.DEAD_HORN_CORAL_FAN, Material.DEAD_HORN_CORAL_WALL_FAN, Material.DEAD_TUBE_CORAL_FAN, Material.DEAD_TUBE_CORAL_WALL_FAN, Material.DRAGON_EGG, Material.FARMLAND, Material.FIRE_CORAL, Material.FIRE_CORAL_FAN, Material.FIRE_CORAL_WALL_FAN, Material.FROSTED_ICE, Material.GLASS, Material.GLASS_PANE, Material.GRAY_BANNER, Material.GRAY_BED, Material.GRAY_STAINED_GLASS, Material.GRAY_STAINED_GLASS_PANE, Material.GRAY_WALL_BANNER, Material.GREEN_BANNER, Material.GREEN_BED, Material.GREEN_STAINED_GLASS, Material.GREEN_STAINED_GLASS_PANE, Material.GREEN_WALL_BANNER, Material.HEAVY_WEIGHTED_PRESSURE_PLATE, Material.HOPPER, Material.HORN_CORAL, Material.HORN_CORAL_FAN, Material.HORN_CORAL_WALL_FAN, Material.ICE, Material.IRON_BARS, Material.IRON_DOOR, Material.IRON_TRAPDOOR, Material.JUNGLE_DOOR, Material.JUNGLE_FENCE, Material.JUNGLE_FENCE_GATE, Material.JUNGLE_LEAVES, Material.JUNGLE_PRESSURE_PLATE, Material.JUNGLE_SLAB, Material.JUNGLE_STAIRS, Material.JUNGLE_TRAPDOOR, Material.KELP, Material.KELP_PLANT, Material.LIGHT_BLUE_BANNER, Material.LIGHT_BLUE_BED, Material.LIGHT_BLUE_STAINED_GLASS, Material.LIGHT_BLUE_STAINED_GLASS_PANE, Material.LIGHT_BLUE_WALL_BANNER, Material.LIGHT_GRAY_BANNER, Material.LIGHT_GRAY_BED, Material.LIGHT_GRAY_STAINED_GLASS, Material.LIGHT_GRAY_STAINED_GLASS_PANE, Material.LIGHT_GRAY_WALL_BANNER, Material.LIGHT_WEIGHTED_PRESSURE_PLATE, Material.LIME_BANNER, Material.LIME_BED, Material.LIME_STAINED_GLASS, Material.LIME_STAINED_GLASS_PANE, Material.LIME_WALL_BANNER, Material.MAGENTA_BANNER, Material.MAGENTA_BED, Material.MAGENTA_STAINED_GLASS, Material.MAGENTA_STAINED_GLASS_PANE, Material.MAGENTA_WALL_BANNER, Material.MOSSY_COBBLESTONE_WALL, Material.MOVING_PISTON, Material.NETHER_BRICK_FENCE, Material.NETHER_BRICK_SLAB, Material.NETHER_BRICK_STAIRS, Material.OAK_DOOR, Material.OAK_FENCE, Material.OAK_FENCE_GATE, Material.OAK_LEAVES, Material.OAK_PRESSURE_PLATE, Material.OAK_SLAB, Material.OAK_STAIRS, Material.OAK_TRAPDOOR, Material.ORANGE_BANNER, Material.ORANGE_BED, Material.ORANGE_STAINED_GLASS, Material.ORANGE_STAINED_GLASS_PANE, Material.ORANGE_WALL_BANNER, Material.PACKED_ICE, Material.PETRIFIED_OAK_SLAB, Material.PINK_BANNER, Material.PINK_BED, Material.PINK_STAINED_GLASS, Material.PINK_STAINED_GLASS_PANE, Material.PINK_WALL_BANNER, Material.PISTON, Material.PISTON_HEAD, Material.PRISMARINE_BRICK_SLAB, Material.PRISMARINE_BRICK_STAIRS, Material.PRISMARINE_SLAB, Material.PRISMARINE_STAIRS, Material.PURPLE_BANNER, Material.PURPLE_BED, Material.PURPLE_STAINED_GLASS, Material.PURPLE_STAINED_GLASS_PANE, Material.PURPLE_WALL_BANNER, Material.PURPUR_SLAB, Material.PURPUR_STAIRS, Material.QUARTZ_SLAB, Material.QUARTZ_STAIRS, Material.RED_BANNER, Material.RED_BED, Material.RED_SANDSTONE_SLAB, Material.RED_SANDSTONE_STAIRS, Material.RED_STAINED_GLASS, Material.RED_STAINED_GLASS_PANE, Material.RED_WALL_BANNER, Material.SANDSTONE_SLAB, Material.SANDSTONE_STAIRS, Material.SEAGRASS, Material.SEA_PICKLE, Material.SIGN, Material.SLIME_BLOCK, Material.SPAWNER, Material.SPRUCE_DOOR, Material.SPRUCE_FENCE, Material.SPRUCE_FENCE_GATE, Material.SPRUCE_LEAVES, Material.SPRUCE_PRESSURE_PLATE, Material.SPRUCE_SLAB, Material.SPRUCE_STAIRS, Material.SPRUCE_TRAPDOOR, Material.STICKY_PISTON, Material.STONE_BRICK_SLAB, Material.STONE_BRICK_STAIRS, Material.STONE_PRESSURE_PLATE, Material.STONE_SLAB, Material.TALL_SEAGRASS, Material.TUBE_CORAL, Material.TUBE_CORAL_FAN, Material.TUBE_CORAL_WALL_FAN, Material.TURTLE_EGG, Material.WALL_SIGN, Material.WATER, Material.WHITE_BANNER, Material.WHITE_BED, Material.WHITE_STAINED_GLASS, Material.WHITE_STAINED_GLASS_PANE, Material.WHITE_WALL_BANNER, Material.YELLOW_BANNER, Material.YELLOW_BED, Material.YELLOW_STAINED_GLASS, Material.YELLOW_STAINED_GLASS_PANE, Material.YELLOW_WALL_BANNER }; } private void initBlockIds() { this.materialIds = new HashMap<>(); Block.REGISTRY_ID.iterator().forEachRemaining(blockData -> { Material material = CraftBlockData.fromData(blockData).getMaterial(); if(material.isBlock()) { int materialId = Block.REGISTRY_ID.getId(blockData); Set<Integer> ids = this.materialIds.get(material); if (ids == null) { this.materialIds.put(material, ids = new HashSet<>()); } ids.add(materialId); } }); } public ConfigDefaults getConfigDefaults() { return this.configDefaults; } public Material[] getExtraTransparentBlocks() { return this.extraTransparentBlocks; } public void setMaxLoadedCacheFiles(int value) { this.maxLoadedCacheFiles = value; } public INBT createNBT() { return new NBT(); } public IChunkCache createChunkCache() { return new ChunkCache(this.maxLoadedCacheFiles); } public void updateBlockTileEntity(BlockCoord blockCoord, Player player) { CraftWorld world = (CraftWorld)player.getWorld(); TileEntity tileEntity = world.getTileEntityAt(blockCoord.x, blockCoord.y, blockCoord.z); if (tileEntity == null) { return; } Packet<?> packet = tileEntity.getUpdatePacket(); if (packet != null) { CraftPlayer player2 = (CraftPlayer)player; player2.getHandle().playerConnection.sendPacket(packet); } } public void notifyBlockChange(World world, IBlockInfo blockInfo) { BlockPosition blockPosition = new BlockPosition(blockInfo.getX(), blockInfo.getY(), blockInfo.getZ()); IBlockData blockData = ((BlockInfo)blockInfo).getBlockData(); ((CraftWorld)world).getHandle().notify(blockPosition, blockData, blockData, 0); } public int getBlockLightLevel(World world, int x, int y, int z) { return ((CraftWorld)world).getHandle().getLightLevel(new BlockPosition(x, y, z)); } public IBlockInfo getBlockInfo(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, false); return blockData != null ? new BlockInfo(x, y, z, blockData) : null; } public int loadChunkAndGetBlockId(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, true); return blockData != null ? Block.getCombinedId(blockData): -1; } public String getTextFromChatComponent(String json) { IChatBaseComponent component = IChatBaseComponent.ChatSerializer.a(json); return CraftChatMessage.fromComponent(component); } public boolean isHoe(Material item) { return item == Material.WOODEN_HOE || item == Material.IRON_HOE || item == Material.GOLDEN_HOE || item == Material.DIAMOND_HOE; } public boolean isSign(int combinedBlockId) { return BLOCK_ID_SIGNS.contains(combinedBlockId); } public boolean isAir(int combinedBlockId) { return BLOCK_ID_AIRS.contains(combinedBlockId); } public boolean isTileEntity(int combinedBlockId) { return Block.getByCombinedId(combinedBlockId).getBlock().isTileEntity(); } public int getCaveAirBlockId() { return BLOCK_ID_CAVE_AIR; } public int getBitsPerBlock() { return BITS_PER_BLOCK; } public boolean canApplyPhysics(Material blockMaterial) { return blockMaterial == Material.AIR || blockMaterial == Material.CAVE_AIR || blockMaterial == Material.VOID_AIR || blockMaterial == Material.FIRE || blockMaterial == Material.WATER || blockMaterial == Material.LAVA; } public Set<Integer> getMaterialIds(Material material) { return this.materialIds.get(material); } public boolean sendBlockChange(Player player, Location blockLocation) { IBlockData blockData = getBlockData(blockLocation.getWorld(), blockLocation.getBlockX(), blockLocation.getBlockY(), blockLocation.getBlockZ(), false); if(blockData == null) return false; CraftBlockData craftBlockData = CraftBlockData.fromData(blockData); player.sendBlockChange(blockLocation, craftBlockData); return true; } private static IBlockData getBlockData(World world, int x, int y, int z, boolean loadChunk) { int chunkX = x >> 4; int chunkZ = z >> 4; WorldServer worldServer = ((CraftWorld)world).getHandle(); ChunkProviderServer chunkProviderServer = worldServer.getChunkProviderServer(); if(!loadChunk && !chunkProviderServer.isLoaded(chunkX, chunkZ)) return null; Chunk chunk = chunkProviderServer.getOrLoadChunkAt(chunkX, chunkZ); return chunk != null ? chunk.getBlockData(x, y, z) : null; } private Set<Integer> convertMaterialsToSet(Material[] materials) { Set<Integer> ids = new HashSet<>(); for(Material material : materials) { ids.addAll(getMaterialIds(material)); } return ids; } private int[] convertMaterialsToIds(Material[] materials) { Set<Integer> ids = convertMaterialsToSet(materials); int[] result = new int[ids.size()]; int index = 0; for(int id : ids) { result[index++] = id; } return result; } }
16,624
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkCache.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_13_R1/src/main/java/com/lishid/orebfuscator/nms/v1_13_R1/ChunkCache.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_13_R1; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.util.HashMap; import net.minecraft.server.v1_13_R1.RegionFile; import com.lishid.orebfuscator.nms.IChunkCache; public class ChunkCache implements IChunkCache { private static final HashMap<File, RegionFile> cachedRegionFiles = new HashMap<File, RegionFile>(); private int maxLoadedCacheFiles; public ChunkCache(int maxLoadedCacheFiles) { this.maxLoadedCacheFiles = maxLoadedCacheFiles; } public DataInputStream getInputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.a(x & 0x1F, z & 0x1F); } public DataOutputStream getOutputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.c(x & 0x1F, z & 0x1F); } public void closeCacheFiles() { closeCacheFilesInternal(); } private synchronized RegionFile getRegionFile(File folder, int x, int z) { File path = new File(folder, "region"); File file = new File(path, "r." + (x >> 5) + "." + (z >> 5) + ".mcr"); try { RegionFile regionFile = cachedRegionFiles.get(file); if (regionFile != null) { return regionFile; } if (!path.exists()) { path.mkdirs(); } if (cachedRegionFiles.size() >= this.maxLoadedCacheFiles) { closeCacheFiles(); } regionFile = new RegionFile(file); cachedRegionFiles.put(file, regionFile); return regionFile; } catch (Exception e) { try { file.delete(); } catch (Exception e2) { } } return null; } private synchronized void closeCacheFilesInternal() { for (RegionFile regionFile : cachedRegionFiles.values()) { try { if (regionFile != null) regionFile.c(); } catch (Exception e) { e.printStackTrace(); } } cachedRegionFiles.clear(); } }
2,352
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
BlockInfo.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_13_R1/src/main/java/com/lishid/orebfuscator/nms/v1_13_R1/BlockInfo.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_13_R1; import net.minecraft.server.v1_13_R1.Block; import net.minecraft.server.v1_13_R1.IBlockData; import com.lishid.orebfuscator.nms.IBlockInfo; public class BlockInfo implements IBlockInfo { private int x; private int y; private int z; private IBlockData blockData; public BlockInfo(int x, int y, int z, IBlockData blockData) { this.x = x; this.y = y; this.z = z; this.blockData = blockData; } public int getX() { return this.x; } public int getY() { return this.y; } public int getZ() { return this.z; } public int getCombinedId() { return Block.getCombinedId(this.blockData); } public IBlockData getBlockData() { return this.blockData; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof BlockInfo)) { return false; } BlockInfo object = (BlockInfo) other; return this.x == object.x && this.y == object.y && this.z == object.z; } @Override public int hashCode() { return this.x ^ this.y ^ this.z; } @Override public String toString() { return this.x + " " + this.y + " " + this.z; } }
1,182
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NBT.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_9_R2/src/main/java/com/lishid/orebfuscator/nms/v1_9_R2/NBT.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_9_R2; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.IOException; import net.minecraft.server.v1_9_R2.NBTCompressedStreamTools; import net.minecraft.server.v1_9_R2.NBTTagCompound; import com.lishid.orebfuscator.nms.INBT; public class NBT implements INBT { NBTTagCompound nbt = new NBTTagCompound(); public void reset() { nbt = new NBTTagCompound(); } public void setInt(String tag, int value) { nbt.setInt(tag, value); } public void setLong(String tag, long value) { nbt.setLong(tag, value); } public void setByteArray(String tag, byte[] value) { nbt.setByteArray(tag, value); } public void setIntArray(String tag, int[] value) { nbt.setIntArray(tag, value); } public int getInt(String tag) { return nbt.getInt(tag); } public long getLong(String tag) { return nbt.getLong(tag); } public byte[] getByteArray(String tag) { return nbt.getByteArray(tag); } public int[] getIntArray(String tag) { return nbt.getIntArray(tag); } public void Read(DataInput stream) throws IOException { nbt = NBTCompressedStreamTools.a((DataInputStream) stream); } public void Write(DataOutput stream) throws IOException { NBTCompressedStreamTools.a(nbt, stream); } }
1,485
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NmsManager.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_9_R2/src/main/java/com/lishid/orebfuscator/nms/v1_9_R2/NmsManager.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_9_R2; import com.google.common.collect.ImmutableList; import com.lishid.orebfuscator.types.ConfigDefaults; import net.minecraft.server.v1_9_R2.Block; import net.minecraft.server.v1_9_R2.BlockPosition; import net.minecraft.server.v1_9_R2.Chunk; import net.minecraft.server.v1_9_R2.ChunkProviderServer; import net.minecraft.server.v1_9_R2.IBlockData; import net.minecraft.server.v1_9_R2.IChatBaseComponent; import net.minecraft.server.v1_9_R2.Packet; import net.minecraft.server.v1_9_R2.TileEntity; import net.minecraft.server.v1_9_R2.WorldServer; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.craftbukkit.v1_9_R2.CraftWorld; import org.bukkit.craftbukkit.v1_9_R2.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_9_R2.util.CraftChatMessage; import org.bukkit.entity.Player; import com.lishid.orebfuscator.nms.IBlockInfo; import com.lishid.orebfuscator.nms.IChunkCache; import com.lishid.orebfuscator.nms.INBT; import com.lishid.orebfuscator.nms.INmsManager; import com.lishid.orebfuscator.types.BlockCoord; import java.util.HashSet; import java.util.Set; public class NmsManager implements INmsManager { private ConfigDefaults configDefaults; private Material[] extraTransparentBlocks; private int maxLoadedCacheFiles; public NmsManager() { this.configDefaults = new ConfigDefaults(); // Default World this.configDefaults.defaultProximityHiderBlockIds = convertMaterialsToIds(new Material[] { Material.DISPENSER, Material.MOB_SPAWNER, Material.CHEST, Material.HOPPER, Material.WORKBENCH, Material.FURNACE, Material.BURNING_FURNACE, Material.ENCHANTMENT_TABLE, Material.EMERALD_ORE, Material.ENDER_CHEST, Material.ANVIL, Material.TRAPPED_CHEST, Material.DIAMOND_ORE }); this.configDefaults.defaultDarknessBlockIds = convertMaterialsToIds(new Material[] { Material.MOB_SPAWNER, Material.CHEST }); this.configDefaults.defaultMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.defaultProximityHiderSpecialBlockId = getMaterialIds(Material.STONE).iterator().next(); // The End this.configDefaults.endWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.BEDROCK, Material.OBSIDIAN, Material.ENDER_STONE, Material.PURPUR_BLOCK, Material.END_BRICKS }); this.configDefaults.endWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.ENDER_STONE }); this.configDefaults.endWorldMode1BlockId = getMaterialIds(Material.ENDER_STONE).iterator().next(); this.configDefaults.endWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.ENDER_STONE }); // Nether World this.configDefaults.netherWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.GRAVEL, Material.NETHERRACK, Material.SOUL_SAND, Material.NETHER_BRICK, Material.QUARTZ_ORE }); this.configDefaults.netherWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK, Material.QUARTZ_ORE }); this.configDefaults.netherWorldMode1BlockId = getMaterialIds(Material.NETHERRACK).iterator().next(); this.configDefaults.netherWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK }); // Normal World this.configDefaults.normalWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.STONE, Material.COBBLESTONE, Material.WOOD, Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.TNT, Material.MOSSY_COBBLESTONE, Material.OBSIDIAN, Material.DIAMOND_ORE, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.CHEST, Material.DIAMOND_ORE, Material.ENDER_CHEST, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.normalWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.STONE }); // Extra transparent blocks this.extraTransparentBlocks = new Material[] { Material.ACACIA_DOOR, Material.ACACIA_FENCE, Material.ACACIA_FENCE_GATE, Material.ACACIA_STAIRS, Material.ANVIL, Material.BEACON, Material.BED_BLOCK, Material.BIRCH_DOOR, Material.BIRCH_FENCE, Material.BIRCH_FENCE_GATE, Material.BIRCH_WOOD_STAIRS, Material.BREWING_STAND, Material.BRICK_STAIRS, Material.CACTUS, Material.CAKE_BLOCK, Material.CAULDRON, Material.COBBLESTONE_STAIRS, Material.COBBLE_WALL, Material.DARK_OAK_DOOR, Material.DARK_OAK_FENCE, Material.DARK_OAK_FENCE_GATE, Material.DARK_OAK_STAIRS, Material.DAYLIGHT_DETECTOR, Material.DAYLIGHT_DETECTOR_INVERTED, Material.DRAGON_EGG, Material.ENCHANTMENT_TABLE, Material.FENCE, Material.FENCE_GATE, Material.GLASS, Material.HOPPER, Material.ICE, Material.IRON_DOOR_BLOCK, Material.IRON_FENCE, Material.IRON_PLATE, Material.IRON_TRAPDOOR, Material.JUNGLE_DOOR, Material.JUNGLE_FENCE, Material.JUNGLE_FENCE_GATE, Material.JUNGLE_WOOD_STAIRS, Material.LAVA, Material.LEAVES, Material.LEAVES_2, Material.MOB_SPAWNER, Material.NETHER_BRICK_STAIRS, Material.NETHER_FENCE, Material.PACKED_ICE, Material.PISTON_BASE, Material.PISTON_EXTENSION, Material.PISTON_MOVING_PIECE, Material.PISTON_STICKY_BASE, Material.PURPUR_SLAB, Material.PURPUR_STAIRS, Material.QUARTZ_STAIRS, Material.RED_SANDSTONE_STAIRS, Material.SANDSTONE_STAIRS, Material.SIGN_POST, Material.SLIME_BLOCK, Material.SMOOTH_STAIRS, Material.SPRUCE_DOOR, Material.SPRUCE_FENCE, Material.SPRUCE_FENCE_GATE, Material.SPRUCE_WOOD_STAIRS, Material.STAINED_GLASS, Material.STAINED_GLASS_PANE, Material.STANDING_BANNER, Material.STATIONARY_LAVA, Material.STATIONARY_WATER, Material.STEP, Material.STONE_PLATE, Material.STONE_SLAB2, Material.THIN_GLASS, Material.TRAP_DOOR, Material.WALL_BANNER, Material.WALL_SIGN, Material.WATER, Material.WEB, Material.WOODEN_DOOR, Material.WOOD_PLATE, Material.WOOD_STAIRS, Material.WOOD_STEP }; } public ConfigDefaults getConfigDefaults() { return this.configDefaults; } public Material[] getExtraTransparentBlocks() { return this.extraTransparentBlocks; } public void setMaxLoadedCacheFiles(int value) { this.maxLoadedCacheFiles = value; } public INBT createNBT() { return new NBT(); } public IChunkCache createChunkCache() { return new ChunkCache(this.maxLoadedCacheFiles); } public void updateBlockTileEntity(BlockCoord blockCoord, Player player) { CraftWorld world = (CraftWorld)player.getWorld(); TileEntity tileEntity = world.getTileEntityAt(blockCoord.x, blockCoord.y, blockCoord.z); if (tileEntity == null) { return; } Packet<?> packet = tileEntity.getUpdatePacket(); if (packet != null) { CraftPlayer player2 = (CraftPlayer)player; player2.getHandle().playerConnection.sendPacket(packet); } } public void notifyBlockChange(World world, IBlockInfo blockInfo) { BlockPosition blockPosition = new BlockPosition(blockInfo.getX(), blockInfo.getY(), blockInfo.getZ()); IBlockData blockData = ((BlockInfo)blockInfo).getBlockData(); ((CraftWorld)world).getHandle().notify(blockPosition, blockData, blockData, 0); } public int getBlockLightLevel(World world, int x, int y, int z) { return ((CraftWorld)world).getHandle().getLightLevel(new BlockPosition(x, y, z)); } public IBlockInfo getBlockInfo(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, false); return blockData != null ? new BlockInfo(x, y, z, blockData) : null; } public int loadChunkAndGetBlockId(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, true); return blockData != null ? Block.getId(blockData.getBlock()): -1; } public String getTextFromChatComponent(String json) { IChatBaseComponent component = IChatBaseComponent.ChatSerializer.a(json); return CraftChatMessage.fromComponent(component); } public boolean isHoe(Material item) { return item == Material.WOOD_HOE || item == Material.IRON_HOE || item == Material.GOLD_HOE || item == Material.DIAMOND_HOE; } @SuppressWarnings("deprecation") public boolean isSign(int combinedBlockId) { int typeId = combinedBlockId >> 4; return typeId == Material.WALL_SIGN.getId() || typeId == Material.SIGN_POST.getId(); } public boolean isAir(int combinedBlockId) { return combinedBlockId == 0; } public boolean isTileEntity(int combinedBlockId) { return Block.getByCombinedId(combinedBlockId).getBlock().isTileEntity(); } public int getCaveAirBlockId() { return 0; } public int getBitsPerBlock() { return 13; } public boolean canApplyPhysics(Material blockMaterial) { return blockMaterial == Material.AIR || blockMaterial == Material.FIRE || blockMaterial == Material.WATER || blockMaterial == Material.STATIONARY_WATER || blockMaterial == Material.LAVA || blockMaterial == Material.STATIONARY_LAVA; } @SuppressWarnings("deprecation") public Set<Integer> getMaterialIds(Material material) { Set<Integer> ids = new HashSet<>(); int blockId = material.getId() << 4; Block block = Block.getById(material.getId()); ImmutableList<IBlockData> blockDataList = block.t().a(); for(IBlockData blockData : blockDataList) { ids.add(blockId | block.toLegacyData(blockData)); } return ids; } @SuppressWarnings("deprecation") public boolean sendBlockChange(Player player, Location blockLocation) { IBlockData blockData = getBlockData(blockLocation.getWorld(), blockLocation.getBlockX(), blockLocation.getBlockY(), blockLocation.getBlockZ(), false); if(blockData == null) return false; Block block = blockData.getBlock(); int blockId = Block.getId(block); byte meta = (byte)block.toLegacyData(blockData); player.sendBlockChange(blockLocation, blockId, meta); return true; } private static IBlockData getBlockData(World world, int x, int y, int z, boolean loadChunk) { int chunkX = x >> 4; int chunkZ = z >> 4; WorldServer worldServer = ((CraftWorld)world).getHandle(); ChunkProviderServer chunkProviderServer = worldServer.getChunkProviderServer(); if(!loadChunk && !chunkProviderServer.isLoaded(chunkX, chunkZ)) return null; Chunk chunk = chunkProviderServer.getOrLoadChunkAt(chunkX, chunkZ); return chunk != null ? chunk.getBlockData(new BlockPosition(x, y, z)) : null; } private Set<Integer> convertMaterialsToSet(Material[] materials) { Set<Integer> ids = new HashSet<>(); for(Material material : materials) { ids.addAll(getMaterialIds(material)); } return ids; } private int[] convertMaterialsToIds(Material[] materials) { Set<Integer> ids = convertMaterialsToSet(materials); int[] result = new int[ids.size()]; int index = 0; for(int id : ids) { result[index++] = id; } return result; } }
11,666
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkCache.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_9_R2/src/main/java/com/lishid/orebfuscator/nms/v1_9_R2/ChunkCache.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_9_R2; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.util.HashMap; import net.minecraft.server.v1_9_R2.RegionFile; import com.lishid.orebfuscator.nms.IChunkCache; public class ChunkCache implements IChunkCache { private static final HashMap<File, RegionFile> cachedRegionFiles = new HashMap<File, RegionFile>(); private int maxLoadedCacheFiles; public ChunkCache(int maxLoadedCacheFiles) { this.maxLoadedCacheFiles = maxLoadedCacheFiles; } public DataInputStream getInputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.a(x & 0x1F, z & 0x1F); } public DataOutputStream getOutputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.b(x & 0x1F, z & 0x1F); } public void closeCacheFiles() { closeCacheFilesInternal(); } private synchronized RegionFile getRegionFile(File folder, int x, int z) { File path = new File(folder, "region"); File file = new File(path, "r." + (x >> 5) + "." + (z >> 5) + ".mcr"); try { RegionFile regionFile = cachedRegionFiles.get(file); if (regionFile != null) { return regionFile; } if (!path.exists()) { path.mkdirs(); } if (cachedRegionFiles.size() >= this.maxLoadedCacheFiles) { closeCacheFiles(); } regionFile = new RegionFile(file); cachedRegionFiles.put(file, regionFile); return regionFile; } catch (Exception e) { try { file.delete(); } catch (Exception e2) { } } return null; } private synchronized void closeCacheFilesInternal() { for (RegionFile regionFile : cachedRegionFiles.values()) { try { if (regionFile != null) regionFile.c(); } catch (Exception e) { e.printStackTrace(); } } cachedRegionFiles.clear(); } }
2,350
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
BlockInfo.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_9_R2/src/main/java/com/lishid/orebfuscator/nms/v1_9_R2/BlockInfo.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_9_R2; import net.minecraft.server.v1_9_R2.Block; import net.minecraft.server.v1_9_R2.IBlockData; import com.lishid.orebfuscator.nms.IBlockInfo; public class BlockInfo implements IBlockInfo { private int x; private int y; private int z; private IBlockData blockData; public BlockInfo(int x, int y, int z, IBlockData blockData) { this.x = x; this.y = y; this.z = z; this.blockData = blockData; } public int getX() { return this.x; } public int getY() { return this.y; } public int getZ() { return this.z; } public int getCombinedId() { Block block = this.blockData.getBlock(); return (Block.getId(block) << 4) | block.toLegacyData(this.blockData); } public IBlockData getBlockData() { return this.blockData; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof BlockInfo)) { return false; } BlockInfo object = (BlockInfo) other; return this.x == object.x && this.y == object.y && this.z == object.z; } @Override public int hashCode() { return this.x ^ this.y ^ this.z; } @Override public String toString() { return this.x + " " + this.y + " " + this.z; } }
1,249
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NBT.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_10_R1/src/main/java/com/lishid/orebfuscator/nms/v1_10_R1/NBT.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_10_R1; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.IOException; import net.minecraft.server.v1_10_R1.NBTCompressedStreamTools; import net.minecraft.server.v1_10_R1.NBTTagCompound; import com.lishid.orebfuscator.nms.INBT; public class NBT implements INBT { NBTTagCompound nbt = new NBTTagCompound(); public void reset() { nbt = new NBTTagCompound(); } public void setInt(String tag, int value) { nbt.setInt(tag, value); } public void setLong(String tag, long value) { nbt.setLong(tag, value); } public void setByteArray(String tag, byte[] value) { nbt.setByteArray(tag, value); } public void setIntArray(String tag, int[] value) { nbt.setIntArray(tag, value); } public int getInt(String tag) { return nbt.getInt(tag); } public long getLong(String tag) { return nbt.getLong(tag); } public byte[] getByteArray(String tag) { return nbt.getByteArray(tag); } public int[] getIntArray(String tag) { return nbt.getIntArray(tag); } public void Read(DataInput stream) throws IOException { nbt = NBTCompressedStreamTools.a((DataInputStream) stream); } public void Write(DataOutput stream) throws IOException { NBTCompressedStreamTools.a(nbt, stream); } }
1,489
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NmsManager.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_10_R1/src/main/java/com/lishid/orebfuscator/nms/v1_10_R1/NmsManager.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_10_R1; import com.google.common.collect.ImmutableList; import com.lishid.orebfuscator.types.ConfigDefaults; import net.minecraft.server.v1_10_R1.Block; import net.minecraft.server.v1_10_R1.BlockPosition; import net.minecraft.server.v1_10_R1.Chunk; import net.minecraft.server.v1_10_R1.ChunkProviderServer; import net.minecraft.server.v1_10_R1.IBlockData; import net.minecraft.server.v1_10_R1.IChatBaseComponent; import net.minecraft.server.v1_10_R1.Packet; import net.minecraft.server.v1_10_R1.TileEntity; import net.minecraft.server.v1_10_R1.WorldServer; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.craftbukkit.v1_10_R1.CraftWorld; import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_10_R1.util.CraftChatMessage; import org.bukkit.entity.Player; import com.lishid.orebfuscator.nms.IBlockInfo; import com.lishid.orebfuscator.nms.IChunkCache; import com.lishid.orebfuscator.nms.INBT; import com.lishid.orebfuscator.nms.INmsManager; import com.lishid.orebfuscator.types.BlockCoord; import java.util.HashSet; import java.util.Set; public class NmsManager implements INmsManager { private ConfigDefaults configDefaults; private Material[] extraTransparentBlocks; private int maxLoadedCacheFiles; public NmsManager() { this.configDefaults = new ConfigDefaults(); // Default World this.configDefaults.defaultProximityHiderBlockIds = convertMaterialsToIds(new Material[] { Material.DISPENSER, Material.MOB_SPAWNER, Material.CHEST, Material.HOPPER, Material.WORKBENCH, Material.FURNACE, Material.BURNING_FURNACE, Material.ENCHANTMENT_TABLE, Material.EMERALD_ORE, Material.ENDER_CHEST, Material.ANVIL, Material.TRAPPED_CHEST, Material.DIAMOND_ORE }); this.configDefaults.defaultDarknessBlockIds = convertMaterialsToIds(new Material[] { Material.MOB_SPAWNER, Material.CHEST }); this.configDefaults.defaultMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.defaultProximityHiderSpecialBlockId = getMaterialIds(Material.STONE).iterator().next(); // The End this.configDefaults.endWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.BEDROCK, Material.OBSIDIAN, Material.ENDER_STONE, Material.PURPUR_BLOCK, Material.END_BRICKS }); this.configDefaults.endWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.ENDER_STONE }); this.configDefaults.endWorldMode1BlockId = getMaterialIds(Material.ENDER_STONE).iterator().next(); this.configDefaults.endWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.ENDER_STONE }); // Nether World this.configDefaults.netherWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.GRAVEL, Material.NETHERRACK, Material.SOUL_SAND, Material.NETHER_BRICK, Material.QUARTZ_ORE }); this.configDefaults.netherWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK, Material.QUARTZ_ORE }); this.configDefaults.netherWorldMode1BlockId = getMaterialIds(Material.NETHERRACK).iterator().next(); this.configDefaults.netherWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK }); // Normal World this.configDefaults.normalWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.STONE, Material.COBBLESTONE, Material.WOOD, Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.TNT, Material.MOSSY_COBBLESTONE, Material.OBSIDIAN, Material.DIAMOND_ORE, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.CHEST, Material.DIAMOND_ORE, Material.ENDER_CHEST, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.normalWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.STONE }); // Extra transparent blocks this.extraTransparentBlocks = new Material[] { Material.ACACIA_DOOR, Material.ACACIA_FENCE, Material.ACACIA_FENCE_GATE, Material.ACACIA_STAIRS, Material.ANVIL, Material.BEACON, Material.BED_BLOCK, Material.BIRCH_DOOR, Material.BIRCH_FENCE, Material.BIRCH_FENCE_GATE, Material.BIRCH_WOOD_STAIRS, Material.BREWING_STAND, Material.BRICK_STAIRS, Material.CACTUS, Material.CAKE_BLOCK, Material.CAULDRON, Material.COBBLESTONE_STAIRS, Material.COBBLE_WALL, Material.DARK_OAK_DOOR, Material.DARK_OAK_FENCE, Material.DARK_OAK_FENCE_GATE, Material.DARK_OAK_STAIRS, Material.DAYLIGHT_DETECTOR, Material.DAYLIGHT_DETECTOR_INVERTED, Material.DRAGON_EGG, Material.ENCHANTMENT_TABLE, Material.FENCE, Material.FENCE_GATE, Material.GLASS, Material.HOPPER, Material.ICE, Material.IRON_DOOR_BLOCK, Material.IRON_FENCE, Material.IRON_PLATE, Material.IRON_TRAPDOOR, Material.JUNGLE_DOOR, Material.JUNGLE_FENCE, Material.JUNGLE_FENCE_GATE, Material.JUNGLE_WOOD_STAIRS, Material.LAVA, Material.LEAVES, Material.LEAVES_2, Material.MOB_SPAWNER, Material.NETHER_BRICK_STAIRS, Material.NETHER_FENCE, Material.PACKED_ICE, Material.PISTON_BASE, Material.PISTON_EXTENSION, Material.PISTON_MOVING_PIECE, Material.PISTON_STICKY_BASE, Material.PURPUR_SLAB, Material.PURPUR_STAIRS, Material.QUARTZ_STAIRS, Material.RED_SANDSTONE_STAIRS, Material.SANDSTONE_STAIRS, Material.SIGN_POST, Material.SLIME_BLOCK, Material.SMOOTH_STAIRS, Material.SPRUCE_DOOR, Material.SPRUCE_FENCE, Material.SPRUCE_FENCE_GATE, Material.SPRUCE_WOOD_STAIRS, Material.STAINED_GLASS, Material.STAINED_GLASS_PANE, Material.STANDING_BANNER, Material.STATIONARY_LAVA, Material.STATIONARY_WATER, Material.STEP, Material.STONE_PLATE, Material.STONE_SLAB2, Material.THIN_GLASS, Material.TRAP_DOOR, Material.WALL_BANNER, Material.WALL_SIGN, Material.WATER, Material.WEB, Material.WOODEN_DOOR, Material.WOOD_PLATE, Material.WOOD_STAIRS, Material.WOOD_STEP }; } public ConfigDefaults getConfigDefaults() { return this.configDefaults; } public Material[] getExtraTransparentBlocks() { return this.extraTransparentBlocks; } public void setMaxLoadedCacheFiles(int value) { this.maxLoadedCacheFiles = value; } public INBT createNBT() { return new NBT(); } @Override public IChunkCache createChunkCache() { return new ChunkCache(this.maxLoadedCacheFiles); } @Override public void updateBlockTileEntity(BlockCoord blockCoord, Player player) { CraftWorld world = (CraftWorld)player.getWorld(); TileEntity tileEntity = world.getTileEntityAt(blockCoord.x, blockCoord.y, blockCoord.z); if (tileEntity == null) { return; } Packet<?> packet = tileEntity.getUpdatePacket(); if (packet != null) { CraftPlayer player2 = (CraftPlayer)player; player2.getHandle().playerConnection.sendPacket(packet); } } @Override public void notifyBlockChange(World world, IBlockInfo blockInfo) { BlockPosition blockPosition = new BlockPosition(blockInfo.getX(), blockInfo.getY(), blockInfo.getZ()); IBlockData blockData = ((BlockInfo)blockInfo).getBlockData(); ((CraftWorld)world).getHandle().notify(blockPosition, blockData, blockData, 0); } @Override public int getBlockLightLevel(World world, int x, int y, int z) { return ((CraftWorld)world).getHandle().getLightLevel(new BlockPosition(x, y, z)); } @Override public IBlockInfo getBlockInfo(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, false); return blockData != null ? new BlockInfo(x, y, z, blockData) : null; } @Override public int loadChunkAndGetBlockId(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, true); return blockData != null ? Block.getId(blockData.getBlock()): -1; } @Override public String getTextFromChatComponent(String json) { IChatBaseComponent component = IChatBaseComponent.ChatSerializer.a(json); return CraftChatMessage.fromComponent(component); } public boolean isHoe(Material item) { return item == Material.WOOD_HOE || item == Material.IRON_HOE || item == Material.GOLD_HOE || item == Material.DIAMOND_HOE; } @SuppressWarnings("deprecation") public boolean isSign(int combinedBlockId) { int typeId = combinedBlockId >> 4; return typeId == Material.WALL_SIGN.getId() || typeId == Material.SIGN_POST.getId(); } public boolean isAir(int combinedBlockId) { return combinedBlockId == 0; } public boolean isTileEntity(int combinedBlockId) { return Block.getByCombinedId(combinedBlockId).getBlock().isTileEntity(); } public int getCaveAirBlockId() { return 0; } public int getBitsPerBlock() { return 13; } public boolean canApplyPhysics(Material blockMaterial) { return blockMaterial == Material.AIR || blockMaterial == Material.FIRE || blockMaterial == Material.WATER || blockMaterial == Material.STATIONARY_WATER || blockMaterial == Material.LAVA || blockMaterial == Material.STATIONARY_LAVA; } @SuppressWarnings("deprecation") public Set<Integer> getMaterialIds(Material material) { Set<Integer> ids = new HashSet<>(); int blockId = material.getId() << 4; Block block = Block.getById(material.getId()); ImmutableList<IBlockData> blockDataList = block.t().a(); for(IBlockData blockData : blockDataList) { ids.add(blockId | block.toLegacyData(blockData)); } return ids; } @SuppressWarnings("deprecation") public boolean sendBlockChange(Player player, Location blockLocation) { IBlockData blockData = getBlockData(blockLocation.getWorld(), blockLocation.getBlockX(), blockLocation.getBlockY(), blockLocation.getBlockZ(), false); if(blockData == null) return false; Block block = blockData.getBlock(); int blockId = Block.getId(block); byte meta = (byte)block.toLegacyData(blockData); player.sendBlockChange(blockLocation, blockId, meta); return true; } private static IBlockData getBlockData(World world, int x, int y, int z, boolean loadChunk) { int chunkX = x >> 4; int chunkZ = z >> 4; WorldServer worldServer = ((CraftWorld)world).getHandle(); ChunkProviderServer chunkProviderServer = worldServer.getChunkProviderServer(); if(!loadChunk && !chunkProviderServer.isLoaded(chunkX, chunkZ)) return null; Chunk chunk = chunkProviderServer.getOrLoadChunkAt(chunkX, chunkZ); return chunk != null ? chunk.getBlockData(new BlockPosition(x, y, z)) : null; } private Set<Integer> convertMaterialsToSet(Material[] materials) { Set<Integer> ids = new HashSet<>(); for(Material material : materials) { ids.addAll(getMaterialIds(material)); } return ids; } private int[] convertMaterialsToIds(Material[] materials) { Set<Integer> ids = convertMaterialsToSet(materials); int[] result = new int[ids.size()]; int index = 0; for(int id : ids) { result[index++] = id; } return result; } }
11,766
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkCache.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_10_R1/src/main/java/com/lishid/orebfuscator/nms/v1_10_R1/ChunkCache.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_10_R1; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.util.HashMap; import net.minecraft.server.v1_10_R1.RegionFile; import com.lishid.orebfuscator.nms.IChunkCache; public class ChunkCache implements IChunkCache { private static final HashMap<File, RegionFile> cachedRegionFiles = new HashMap<File, RegionFile>(); private int maxLoadedCacheFiles; public ChunkCache(int maxLoadedCacheFiles) { this.maxLoadedCacheFiles = maxLoadedCacheFiles; } public DataInputStream getInputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.a(x & 0x1F, z & 0x1F); } public DataOutputStream getOutputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.b(x & 0x1F, z & 0x1F); } public void closeCacheFiles() { closeCacheFilesInternal(); } private synchronized RegionFile getRegionFile(File folder, int x, int z) { File path = new File(folder, "region"); File file = new File(path, "r." + (x >> 5) + "." + (z >> 5) + ".mcr"); try { RegionFile regionFile = cachedRegionFiles.get(file); if (regionFile != null) { return regionFile; } if (!path.exists()) { path.mkdirs(); } if (cachedRegionFiles.size() >= this.maxLoadedCacheFiles) { closeCacheFiles(); } regionFile = new RegionFile(file); cachedRegionFiles.put(file, regionFile); return regionFile; } catch (Exception e) { try { file.delete(); } catch (Exception e2) { } } return null; } private synchronized void closeCacheFilesInternal() { for (RegionFile regionFile : cachedRegionFiles.values()) { try { if (regionFile != null) regionFile.c(); } catch (Exception e) { e.printStackTrace(); } } cachedRegionFiles.clear(); } }
2,352
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
BlockInfo.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_10_R1/src/main/java/com/lishid/orebfuscator/nms/v1_10_R1/BlockInfo.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_10_R1; import net.minecraft.server.v1_10_R1.Block; import net.minecraft.server.v1_10_R1.IBlockData; import com.lishid.orebfuscator.nms.IBlockInfo; public class BlockInfo implements IBlockInfo { private int x; private int y; private int z; private IBlockData blockData; public BlockInfo(int x, int y, int z, IBlockData blockData) { this.x = x; this.y = y; this.z = z; this.blockData = blockData; } public int getX() { return this.x; } public int getY() { return this.y; } public int getZ() { return this.z; } public int getCombinedId() { Block block = this.blockData.getBlock(); return (Block.getId(block) << 4) | block.toLegacyData(this.blockData); } public IBlockData getBlockData() { return this.blockData; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof BlockInfo)) { return false; } BlockInfo object = (BlockInfo) other; return this.x == object.x && this.y == object.y && this.z == object.z; } @Override public int hashCode() { return this.x ^ this.y ^ this.z; } @Override public String toString() { return this.x + " " + this.y + " " + this.z; } }
1,253
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
DeprecatedMethods.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/DeprecatedMethods.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator; import org.bukkit.Material; @SuppressWarnings("deprecation") public class DeprecatedMethods { public static boolean isTransparent(Material material) { return material.isTransparent(); } }
264
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NmsInstance.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/NmsInstance.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator; import com.lishid.orebfuscator.nms.INmsManager; public class NmsInstance { public static INmsManager current; }
188
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
Orebfuscator.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/Orebfuscator.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator; import java.io.*; import java.util.logging.Logger; import com.lishid.orebfuscator.chunkmap.ChunkMapBuffer; import com.lishid.orebfuscator.utils.MaterialHelper; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import com.lishid.orebfuscator.cache.CacheCleaner; import com.lishid.orebfuscator.cache.ObfuscatedDataCache; import com.lishid.orebfuscator.commands.OrebfuscatorCommandExecutor; import com.lishid.orebfuscator.config.ConfigManager; import com.lishid.orebfuscator.config.OrebfuscatorConfig; import com.lishid.orebfuscator.hithack.BlockHitManager; import com.lishid.orebfuscator.hook.ProtocolLibHook; import com.lishid.orebfuscator.listeners.OrebfuscatorBlockListener; import com.lishid.orebfuscator.listeners.OrebfuscatorEntityListener; import com.lishid.orebfuscator.listeners.OrebfuscatorPlayerListener; import com.lishid.orebfuscator.nms.INmsManager; import com.lishid.orebfuscator.utils.Globals; /** * Orebfuscator Anti X-RAY * * @author lishid */ public class Orebfuscator extends JavaPlugin { public static final Logger logger = Logger.getLogger("Minecraft.OFC"); public static Orebfuscator instance; public static OrebfuscatorConfig config; public static ConfigManager configManager; private boolean isProtocolLibFound; public boolean getIsProtocolLibFound() { return this.isProtocolLibFound; } @SuppressWarnings("deprecation") @Override public void onEnable() { // Get plugin manager PluginManager pm = getServer().getPluginManager(); instance = this; NmsInstance.current = createNmsManager(); MaterialHelper.init(); ChunkMapBuffer.init(NmsInstance.current.getBitsPerBlock()); // Load configurations loadOrebfuscatorConfig(); makeConfigExample(); this.isProtocolLibFound = pm.getPlugin("ProtocolLib") != null; if (!this.isProtocolLibFound) { Orebfuscator.log("ProtocolLib is not found! Plugin cannot be enabled."); return; } // Orebfuscator events pm.registerEvents(new OrebfuscatorPlayerListener(), this); pm.registerEvents(new OrebfuscatorEntityListener(), this); pm.registerEvents(new OrebfuscatorBlockListener(), this); (new ProtocolLibHook()).register(this); // Run CacheCleaner getServer().getScheduler().runTaskTimerAsynchronously(this, new CacheCleaner(), 0, config.getCacheCleanRate()); } public void loadOrebfuscatorConfig() { if(config == null) { config = new OrebfuscatorConfig(); configManager = new ConfigManager(this, logger, config); } configManager.load(); ObfuscatedDataCache.resetCacheFolder(); NmsInstance.current.setMaxLoadedCacheFiles(config.getMaxLoadedCacheFiles()); //Make sure cache is cleared if config was changed since last start try { ObfuscatedDataCache.checkCacheAndConfigSynchronized(); } catch (IOException e) { e.printStackTrace(); } } private void makeConfigExample() { File outputFile = new File(getDataFolder(), "config.example_enabledworlds.yml"); if(outputFile.exists()) return; InputStream configStream = Orebfuscator.class.getResourceAsStream("/resources/config.example_enabledworlds.yml"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(configStream)); PrintWriter writer = new PrintWriter(outputFile) ) { String line; while ((line = reader.readLine()) != null) { writer.println(line); } } catch (IOException e) { e.printStackTrace(); } } public void reloadOrebfuscatorConfig() { reloadConfig(); loadOrebfuscatorConfig(); } private static INmsManager createNmsManager() { String serverVersion = org.bukkit.Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; if(serverVersion.equals("v1_13_R2")) { return new com.lishid.orebfuscator.nms.v1_13_R2.NmsManager(); } else if(serverVersion.equals("v1_13_R1")) { return new com.lishid.orebfuscator.nms.v1_13_R1.NmsManager(); } else if(serverVersion.equals("v1_12_R1")) { return new com.lishid.orebfuscator.nms.v1_12_R1.NmsManager(); } else if(serverVersion.equals("v1_11_R1")) { return new com.lishid.orebfuscator.nms.v1_11_R1.NmsManager(); } else if(serverVersion.equals("v1_10_R1")) { return new com.lishid.orebfuscator.nms.v1_10_R1.NmsManager(); } else if(serverVersion.equals("v1_9_R2")) { return new com.lishid.orebfuscator.nms.v1_9_R2.NmsManager(); } else if(serverVersion.equals("v1_9_R1")) { return new com.lishid.orebfuscator.nms.v1_9_R1.NmsManager(); } else return null; } @Override public void onDisable() { ObfuscatedDataCache.closeCacheFiles(); BlockHitManager.clearAll(); getServer().getScheduler().cancelTasks(this); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { return OrebfuscatorCommandExecutor.onCommand(sender, command, label, args); } public void runTask(Runnable task) { if (this.isEnabled()) { getServer().getScheduler().runTask(this, task); } } /** * Log an information */ public static void log(String text) { logger.info(Globals.LogPrefix + text); } /** * Log an error */ public static void log(Throwable e) { logger.severe(Globals.LogPrefix + e.toString()); e.printStackTrace(); } /** * Send a message to a player */ public static void message(CommandSender target, String message) { target.sendMessage(ChatColor.AQUA + Globals.LogPrefix + message); } }
6,888
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
MaterialReader.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/config/MaterialReader.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.config; import java.util.*; import java.util.logging.Logger; import com.lishid.orebfuscator.NmsInstance; import com.lishid.orebfuscator.utils.MaterialHelper; import org.bukkit.Material; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.java.JavaPlugin; import com.lishid.orebfuscator.utils.Globals; public class MaterialReader { private static class MaterialResult { public Set<Integer> ids; public String name; public MaterialResult(Set<Integer> ids, String name) { this.ids = ids; this.name = name; } } private JavaPlugin plugin; private Logger logger; public MaterialReader(JavaPlugin plugin, Logger logger) { this.plugin = plugin; this.logger = logger; } private FileConfiguration getConfig() { return this.plugin.getConfig(); } public Set<Integer> getMaterialIds(String materialName) { return getMaterial(materialName, null).ids; } public Integer getMaterialIdByPath(String path, Integer defaultMaterialId, boolean withSave) { boolean hasKey = getConfig().get(path) != null; if(!hasKey && defaultMaterialId == null) { return null; } String materialName = hasKey ? getConfig().getString(path): Integer.toString(defaultMaterialId); MaterialResult material = getMaterial(materialName, defaultMaterialId); if(withSave || hasKey) { getConfig().set(path, material.name); } return material.ids.iterator().next(); } public Integer[] getMaterialIdsByPath(String path, Integer[] defaultMaterials, boolean withSave) { List<String> list; if(getConfig().get(path) != null) { list = getConfig().getStringList(path); withSave = true; } else { if(defaultMaterials != null) { list = new ArrayList<String>(); for(int materialId : defaultMaterials) { list.add(MaterialHelper.getById(materialId).name()); } } else { return null; } } List<Integer> result = new ArrayList<>(); HashSet<String> uniqueNames = new HashSet<>(); for(int i = 0; i < list.size(); i++) { MaterialResult material = getMaterial(list.get(i), null); if(material != null) { uniqueNames.add(material.name); result.addAll(material.ids); } } if(withSave) { list.clear(); list.addAll(uniqueNames); Collections.sort(list); getConfig().set(path, list); } return result.toArray(new Integer[0]); } private MaterialResult getMaterial(String inputMaterialName, Integer defaultMaterialId) { Set<Integer> materialIds = null; String defaultMaterialName = defaultMaterialId != null ? MaterialHelper.getById(defaultMaterialId).name(): null; String materialName = inputMaterialName; try { if(Character.isDigit(materialName.charAt(0))) { int id = Integer.parseInt(materialName); Material obj = MaterialHelper.getById(id); if(obj != null) { materialName = obj.name(); materialIds = new HashSet<>(); materialIds.add(id); } else { if(defaultMaterialId != null) { this.logger.info(Globals.LogPrefix + "Material with ID = " + id + " is not found. Will be used default material: " + defaultMaterialName); materialName = defaultMaterialName; materialIds = new HashSet<>(); materialIds.add(defaultMaterialId); } else { this.logger.info(Globals.LogPrefix + "Material with ID = " + id + " is not found. Skipped."); } } } else { Material obj = Material.getMaterial(materialName.toUpperCase()); if(obj != null) { materialIds = NmsInstance.current.getMaterialIds(obj); } else { if(defaultMaterialId != null) { this.logger.info(Globals.LogPrefix + "Material " + materialName + " is not found. Will be used default material: " + defaultMaterialName); materialName = defaultMaterialName; materialIds = new HashSet<>(); materialIds.add(defaultMaterialId); } else { this.logger.info(Globals.LogPrefix + "Material " + materialName + " is not found. Skipped."); } } } } catch (Exception e) { if(defaultMaterialId != null) { this.logger.info(Globals.LogPrefix + "Invalid material ID or name: " + materialName + ". Will be used default material: " + defaultMaterialName); materialName = defaultMaterialName; materialIds = new HashSet<>(); materialIds.add(defaultMaterialId); } else { this.logger.info(Globals.LogPrefix + "Invalid material ID or name: " + materialName + ". Skipped."); } } return materialIds != null ? new MaterialResult(materialIds, materialName): null; } }
4,916
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
OrebfuscatorConfig.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/config/OrebfuscatorConfig.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.config; import java.util.Map; import org.bukkit.entity.Player; import com.lishid.orebfuscator.Orebfuscator; public class OrebfuscatorConfig { // Caching private boolean useCache; private int maxLoadedCacheFiles; private String cacheLocation; private int deleteCacheFilesAfterDays; // Main engine config private boolean enabled; private boolean updateOnDamage; private int engineMode; private int initialRadius; private int updateRadius; private boolean noObfuscationForMetadata; private String noObfuscationForMetadataTagName; private boolean noObfuscationForOps; private boolean noObfuscationForPermission; private boolean loginNotification; private byte[] transparentBlocks; private WorldConfig defaultWorld; private WorldConfig normalWorld; private WorldConfig endWorld; private WorldConfig netherWorld; private Map<String, WorldConfig> worlds; private boolean proximityHiderEnabled; private static final int antiHitHackDecrementFactor = 1000; private static final int antiHitHackMaxViolation = 15; private static final int proximityHiderRate = 500; private static final long cacheCleanRate = 60 * 60 * 20;//once per hour public boolean isUseCache() { return this.useCache; } public void setUseCache(boolean value) { this.useCache = value; } public int getMaxLoadedCacheFiles() { return this.maxLoadedCacheFiles; } public void setMaxLoadedCacheFiles(int value) { this.maxLoadedCacheFiles = value; } public String getCacheLocation() { return this.cacheLocation; } public void setCacheLocation(String value) { this.cacheLocation = value; } public int getDeleteCacheFilesAfterDays() { return this.deleteCacheFilesAfterDays; } public void setDeleteCacheFilesAfterDays(int value) { this.deleteCacheFilesAfterDays = value; } public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean value) { this.enabled = value; } public boolean isUpdateOnDamage() { return this.updateOnDamage; } public void setUpdateOnDamage(boolean value) { this.updateOnDamage = value; } public int getEngineMode() { return this.engineMode; } public void setEngineMode(int value) { this.engineMode = value; } public int getInitialRadius() { return this.initialRadius; } public void setInitialRadius(int value) { this.initialRadius = value; } public int getUpdateRadius() { return this.updateRadius; } public void setUpdateRadius(int value) { this.updateRadius = value; } public boolean isNoObfuscationForMetadata() { return this.noObfuscationForMetadata; } public void setNoObfuscationForMetadata(boolean value) { this.noObfuscationForMetadata = value; } public String getNoObfuscationForMetadataTagName() { return this.noObfuscationForMetadataTagName; } public void setNoObfuscationForMetadataTagName(String value) { this.noObfuscationForMetadataTagName = value; } public boolean isNoObfuscationForOps() { return this.noObfuscationForOps; } public void setNoObfuscationForOps(boolean value) { this.noObfuscationForOps = value; } public boolean isNoObfuscationForPermission() { return this.noObfuscationForPermission; } public void setNoObfuscationForPermission(boolean value) { this.noObfuscationForPermission = value; } public boolean isLoginNotification() { return this.loginNotification; } public void setLoginNotification(boolean value) { this.loginNotification = value; } public void setTransparentBlocks(byte[] transparentBlocks) { this.transparentBlocks = transparentBlocks; } public WorldConfig getDefaultWorld() { return this.defaultWorld; } public void setDefaultWorld(WorldConfig value) { this.defaultWorld = value; } public WorldConfig getNormalWorld() { return this.normalWorld; } public void setNormalWorld(WorldConfig value) { this.normalWorld = value; } public WorldConfig getEndWorld() { return this.endWorld; } public void setEndWorld(WorldConfig value) { this.endWorld = value; } public WorldConfig getNetherWorld() { return this.netherWorld; } public void setNetherWorld(WorldConfig value) { this.netherWorld = value; } public String getWorldNames() { String worldNames = ""; for(WorldConfig world : this.worlds.values()) { if(worldNames.length() > 0) { worldNames += ", "; } worldNames += world.getName(); } return worldNames; } public WorldConfig getWorld(String name) { return this.worlds.get(name.toLowerCase()); } public void setWorlds(Map<String, WorldConfig> value) { this.worlds = value; } public boolean isProximityHiderEnabled() { return this.proximityHiderEnabled; } public void setProximityHiderEnabled() { this.proximityHiderEnabled = this.normalWorld.getProximityHiderConfig().isEnabled() || this.endWorld.getProximityHiderConfig().isEnabled() || this.netherWorld.getProximityHiderConfig().isEnabled() ; if(!this.proximityHiderEnabled) { for(WorldConfig world : this.worlds.values()) { if(world.getProximityHiderConfig().isEnabled() != null && world.getProximityHiderConfig().isEnabled()) { this.proximityHiderEnabled = true; break; } } } } public int getAntiHitHackDecrementFactor() { return antiHitHackDecrementFactor; } public int getAntiHitHackMaxViolation() { return antiHitHackMaxViolation; } public int getProximityHiderRate() { return proximityHiderRate; } public long getCacheCleanRate() { return cacheCleanRate; } // Helper methods public boolean isBlockTransparent(int id) { return this.transparentBlocks[id] == 1; } public boolean obfuscateForPlayer(Player player) { return !(playerBypassOp(player) || playerBypassPerms(player) || playerBypassMetadata(player)); } public boolean playerBypassOp(Player player) { boolean ret = false; try { ret = this.noObfuscationForOps && player.isOp(); } catch (Exception e) { Orebfuscator.log("Error while obtaining Operator status for player" + player.getName() + ": " + e.getMessage()); e.printStackTrace(); } return ret; } public boolean playerBypassPerms(Player player) { boolean ret = false; try { ret = this.noObfuscationForPermission && player.hasPermission("Orebfuscator.deobfuscate"); } catch (Exception e) { Orebfuscator.log("Error while obtaining permissions for player" + player.getName() + ": " + e.getMessage()); e.printStackTrace(); } return ret; } public boolean playerBypassMetadata(Player player) { boolean ret = false; try { ret = this.noObfuscationForMetadata && player.hasMetadata(this.noObfuscationForMetadataTagName) && player.getMetadata(this.noObfuscationForMetadataTagName).get(0).asBoolean(); } catch (Exception e) { Orebfuscator.log("Error while obtaining metadata for player" + player.getName() + ": " + e.getMessage()); e.printStackTrace(); } return ret; } }
7,936
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
WorldConfig.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/config/WorldConfig.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.config; import com.lishid.orebfuscator.NmsInstance; import com.lishid.orebfuscator.utils.Globals; import com.lishid.orebfuscator.utils.MaterialHelper; import java.util.*; public class WorldConfig { private String name; private Boolean enabled; private Boolean darknessHideBlocks; private Boolean antiTexturePackAndFreecam; private Boolean bypassObfuscationForSignsWithText; private Integer airGeneratorMaxChance; private HashSet<Integer> obfuscateBlocks; private HashSet<Integer> darknessBlocks; private byte[] obfuscateAndProximityBlocks; private Integer[] randomBlocks; private Integer[] randomBlocks2; private Integer mode1BlockId; private int[] paletteBlocks; private ProximityHiderConfig proximityHiderConfig; private boolean initialized; public WorldConfig() { this.proximityHiderConfig = new ProximityHiderConfig(); } public void setDefaults() { this.enabled = true; this.darknessHideBlocks = false; this.antiTexturePackAndFreecam = true; this.bypassObfuscationForSignsWithText = false; this.airGeneratorMaxChance = 43; this.obfuscateBlocks = new HashSet<>(); this.darknessBlocks = new HashSet<>(); for(int blockId : NmsInstance.current.getConfigDefaults().defaultDarknessBlockIds) { this.darknessBlocks.add(blockId); } this.randomBlocks = new Integer[0]; this.randomBlocks2 = this.randomBlocks; this.mode1BlockId = NmsInstance.current.getConfigDefaults().defaultMode1BlockId; this.paletteBlocks = null; this.proximityHiderConfig.setDefaults(); } public void init(WorldConfig baseWorld) { if(this.initialized) { return; } if(baseWorld != null) { if(this.enabled == null) { this.enabled = baseWorld.enabled; } if(this.darknessHideBlocks == null) { this.darknessHideBlocks = baseWorld.darknessHideBlocks; } if(this.antiTexturePackAndFreecam == null) { this.antiTexturePackAndFreecam = baseWorld.antiTexturePackAndFreecam; } if(this.bypassObfuscationForSignsWithText == null) { this.bypassObfuscationForSignsWithText = baseWorld.bypassObfuscationForSignsWithText; } if(this.airGeneratorMaxChance == null) { this.airGeneratorMaxChance = baseWorld.airGeneratorMaxChance; } if(this.obfuscateBlocks == null) { this.obfuscateBlocks = baseWorld.obfuscateBlocks != null ? (HashSet<Integer>)baseWorld.obfuscateBlocks.clone(): null; } if(this.darknessBlocks == null) { this.darknessBlocks = baseWorld.darknessBlocks != null ? (HashSet<Integer>)baseWorld.darknessBlocks.clone(): null; } if(this.randomBlocks == null) { this.randomBlocks = baseWorld.randomBlocks != null ? baseWorld.randomBlocks.clone(): null; this.randomBlocks2 = baseWorld.randomBlocks2 != null ? baseWorld.randomBlocks2.clone(): null; } if(this.mode1BlockId == null) { this.mode1BlockId = baseWorld.mode1BlockId; } this.proximityHiderConfig.init(baseWorld.proximityHiderConfig); setObfuscateAndProximityBlocks(); } setPaletteBlocks(); this.initialized = true; } public boolean isInitialized() { return this.initialized; } public String getName() { return this.name; } public void setName(String value) { this.name = value; } public Boolean isEnabled() { return this.enabled; } public void setEnabled(Boolean value) { this.enabled = value; } public Boolean isDarknessHideBlocks() { return this.darknessHideBlocks; } public void setDarknessHideBlocks(Boolean value) { this.darknessHideBlocks = value; } public Boolean isAntiTexturePackAndFreecam() { return this.antiTexturePackAndFreecam; } public void setAntiTexturePackAndFreecam(Boolean value) { this.antiTexturePackAndFreecam = value; } public Boolean isBypassObfuscationForSignsWithText() { return this.bypassObfuscationForSignsWithText; } public void setBypassObfuscationForSignsWithText(Boolean value) { this.bypassObfuscationForSignsWithText = value; } public Integer getAirGeneratorMaxChance() { return this.airGeneratorMaxChance; } public void setAirGeneratorMaxChance(Integer value) { this.airGeneratorMaxChance = value; } public HashSet<Integer> getObfuscateBlocks() { return this.obfuscateBlocks; } public void setObfuscateBlocks(HashSet<Integer> value) { this.obfuscateBlocks = value; } public void setObfuscateBlocks(Integer[] value) { this.obfuscateBlocks = new HashSet<>(); for(int id : value) { this.obfuscateBlocks.add(id); } } private void setObfuscateAndProximityBlocks() { this.obfuscateAndProximityBlocks = new byte[MaterialHelper.getMaxId() + 1]; setObfuscateMask(this.obfuscateBlocks, false, false); if(this.darknessBlocks != null && this.darknessHideBlocks) { setObfuscateMask(this.darknessBlocks, true, false); } if(this.proximityHiderConfig != null && this.proximityHiderConfig.isEnabled()) { setObfuscateMask(this.proximityHiderConfig.getProximityHiderBlocks(), false, true); } } private void setObfuscateMask(Set<Integer> blockIds, boolean isDarknessBlock, boolean isProximityHider) { for(int blockId : blockIds) { int bits = this.obfuscateAndProximityBlocks[blockId] | Globals.MASK_OBFUSCATE; if(isDarknessBlock) { bits |= Globals.MASK_DARKNESSBLOCK; } if(isProximityHider) { bits |= Globals.MASK_PROXIMITYHIDER; } if(NmsInstance.current.isTileEntity(blockId)) { bits |= Globals.MASK_TILEENTITY; } this.obfuscateAndProximityBlocks[blockId] = (byte)bits; } } public byte[] getObfuscateAndProximityBlocks() { return this.obfuscateAndProximityBlocks; } public HashSet<Integer> getDarknessBlocks() { return this.darknessBlocks; } public void setDarknessBlocks(HashSet<Integer> values) { this.darknessBlocks = values; } public Integer[] getRandomBlocks() { return this.randomBlocks; } public void setRandomBlocks(Integer[] values) { this.randomBlocks = values; this.randomBlocks2 = values; } public void shuffleRandomBlocks() { synchronized (this.randomBlocks) { Collections.shuffle(Arrays.asList(this.randomBlocks)); Collections.shuffle(Arrays.asList(this.randomBlocks2)); } } public Integer getMode1BlockId() { return this.mode1BlockId; } public void setMode1BlockId(Integer value) { this.mode1BlockId = value; } public int[] getPaletteBlocks() { return this.paletteBlocks; } private void setPaletteBlocks() { if(this.randomBlocks == null) { return; } HashSet<Integer> map = new HashSet<Integer>(); map.add(NmsInstance.current.getCaveAirBlockId()); map.add(this.mode1BlockId); if(this.proximityHiderConfig.isUseSpecialBlock()) { map.add(this.proximityHiderConfig.getSpecialBlockID()); } for(Integer id : this.randomBlocks) { if(id != null) { map.add(id); } } int[] paletteBlocks = new int[map.size()]; int index = 0; for(Integer id : map) { paletteBlocks[index++] = id; } this.paletteBlocks = paletteBlocks; } public ProximityHiderConfig getProximityHiderConfig() { return this.proximityHiderConfig; } // Helper methods public int getObfuscatedBits(int id) { return this.obfuscateAndProximityBlocks[id]; } public int getRandomBlock(int index, boolean alternate) { return alternate ? this.randomBlocks2[index] : this.randomBlocks[index]; } }
8,042
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ConfigManager.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/config/ConfigManager.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.config; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import com.lishid.orebfuscator.DeprecatedMethods; import com.lishid.orebfuscator.NmsInstance; import com.lishid.orebfuscator.Orebfuscator; import com.lishid.orebfuscator.utils.MaterialHelper; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.java.JavaPlugin; import com.lishid.orebfuscator.utils.Globals; public class ConfigManager { private static final int CONFIG_VERSION = 13; private JavaPlugin plugin; private Logger logger; private OrebfuscatorConfig orebfuscatorConfig; private MaterialReader materialReader; public ConfigManager(JavaPlugin plugin, Logger logger, OrebfuscatorConfig orebfuscatorConfig) { this.plugin = plugin; this.logger = logger; this.orebfuscatorConfig = orebfuscatorConfig; this.materialReader = new MaterialReader(this.plugin, this.logger); } public WorldConfig getWorld(World world) { if(world == null) { return null; } WorldConfig baseCfg; switch(world.getEnvironment()) { case THE_END: baseCfg = this.orebfuscatorConfig.getEndWorld(); break; case NETHER: baseCfg = this.orebfuscatorConfig.getNetherWorld(); break; default: baseCfg = this.orebfuscatorConfig.getNormalWorld(); break; } WorldConfig cfg = this.orebfuscatorConfig.getWorld(world.getName()); if(cfg == null) { return baseCfg; } if(!cfg.isInitialized()) { cfg.init(baseCfg); this.logger.log(Level.INFO, Globals.LogPrefix + "Config for world '" + world.getName() + "' is initialized."); } return cfg; } public void load() { // Version check int version = getInt("ConfigVersion", CONFIG_VERSION); if (version < CONFIG_VERSION) { if(version <= 12) { new Convert12To13(this.plugin).convert(); logger.info(Globals.LogPrefix + "Configuration file have been converted to new version."); } else { getConfig().set("ConfigVersion", CONFIG_VERSION); } } boolean useCache = getBoolean("Booleans.UseCache", true); int maxLoadedCacheFiles = getInt("Integers.MaxLoadedCacheFiles", 64, 16, 128); String cacheLocation = getString("Strings.CacheLocation", "orebfuscator_cache"); int deleteCacheFilesAfterDays = getInt("Integers.DeleteCacheFilesAfterDays", 0); boolean enabled = getBoolean("Booleans.Enabled", true); boolean updateOnDamage = getBoolean("Booleans.UpdateOnDamage", true); int engineMode = getInt("Integers.EngineMode", 2); if (engineMode != 1 && engineMode != 2) { engineMode = 2; logger.info(Globals.LogPrefix + "EngineMode must be 1 or 2."); } int initialRadius = getInt("Integers.InitialRadius", 1, 0, 2); if (initialRadius == 0) { logger.info(Globals.LogPrefix + "Warning, InitialRadius is 0. This will cause all exposed blocks to be obfuscated."); } int updateRadius = getInt("Integers.UpdateRadius", 2, 1, 5); boolean noObfuscationForMetadata = getBoolean("Booleans.NoObfuscationForMetadata", true); String noObfuscationForMetadataTagName = getString("Strings.NoObfuscationForMetadataTagName", "NPC"); boolean noObfuscationForOps = getBoolean("Booleans.NoObfuscationForOps", false); boolean noObfuscationForPermission = getBoolean("Booleans.NoObfuscationForPermission", false); boolean loginNotification = getBoolean("Booleans.LoginNotification", true); byte[] transparentBlocks = generateTransparentBlocks(engineMode); this.orebfuscatorConfig.setUseCache(useCache); this.orebfuscatorConfig.setMaxLoadedCacheFiles(maxLoadedCacheFiles); this.orebfuscatorConfig.setCacheLocation(cacheLocation); this.orebfuscatorConfig.setDeleteCacheFilesAfterDays(deleteCacheFilesAfterDays); this.orebfuscatorConfig.setEnabled(enabled); this.orebfuscatorConfig.setUpdateOnDamage(updateOnDamage); this.orebfuscatorConfig.setEngineMode(engineMode); this.orebfuscatorConfig.setInitialRadius(initialRadius); this.orebfuscatorConfig.setUpdateRadius(updateRadius); this.orebfuscatorConfig.setNoObfuscationForMetadata(noObfuscationForMetadata); this.orebfuscatorConfig.setNoObfuscationForMetadataTagName(noObfuscationForMetadataTagName); this.orebfuscatorConfig.setNoObfuscationForOps(noObfuscationForOps); this.orebfuscatorConfig.setNoObfuscationForPermission(noObfuscationForPermission); this.orebfuscatorConfig.setLoginNotification(loginNotification); this.orebfuscatorConfig.setTransparentBlocks(transparentBlocks); new WorldReader(this.plugin, this.logger, this.orebfuscatorConfig, this.materialReader).load(); this.orebfuscatorConfig.setProximityHiderEnabled(); this.logger.info(Globals.LogPrefix + "Proximity Hider is " + (this.orebfuscatorConfig.isProximityHiderEnabled() ? "Enabled": "Disabled")); save(); } public void setEngineMode(int value) { getConfig().set("Integers.EngineMode", value); save(); this.orebfuscatorConfig.setEngineMode(value); } public void setUpdateRadius(int value) { getConfig().set("Integers.UpdateRadius", value); save(); this.orebfuscatorConfig.setUpdateRadius(value); } public void setInitialRadius(int value) { getConfig().set("Integers.InitialRadius", value); save(); this.orebfuscatorConfig.setInitialRadius(value); } public void setProximityHiderDistance(int value) { getConfig().set("Integers.ProximityHiderDistance", value); save(); this.orebfuscatorConfig.getDefaultWorld().getProximityHiderConfig().setDistance(value); } public void setNoObfuscationForOps(boolean value) { getConfig().set("Booleans.NoObfuscationForOps", value); save(); this.orebfuscatorConfig.setNoObfuscationForOps(value); } public void setNoObfuscationForPermission(boolean value) { getConfig().set("Booleans.NoObfuscationForPermission", value); save(); this.orebfuscatorConfig.setNoObfuscationForPermission(value); } public void setLoginNotification(boolean value) { getConfig().set("Booleans.LoginNotification", value); save(); this.orebfuscatorConfig.setLoginNotification(value); } public void setUseCache(boolean value) { getConfig().set("Booleans.UseCache", value); save(); this.orebfuscatorConfig.setUseCache(value); } public void setEnabled(boolean value) { getConfig().set("Booleans.Enabled", value); save(); this.orebfuscatorConfig.setEnabled(value); } private FileConfiguration getConfig() { return this.plugin.getConfig(); } private void save() { this.plugin.saveConfig(); } private String getString(String path, String defaultData, boolean withSave) { if (getConfig().get(path) == null) { if(!withSave) { return defaultData; } getConfig().set(path, defaultData); } return getConfig().getString(path, defaultData); } private String getString(String path, String defaultData) { return getString(path, defaultData, true); } private int getInt(String path, int defaultData) { return getInt(path, defaultData, true); } private int getInt(String path, int defaultData, boolean withSave) { if (getConfig().get(path) == null) { if(!withSave) { return defaultData; } getConfig().set(path, defaultData); } return getConfig().getInt(path, defaultData); } private int getInt(String path, int defaultData, int min, int max, boolean withSave) { if (getConfig().get(path) == null && withSave) { getConfig().set(path, defaultData); } int value = getConfig().get(path) != null ? getConfig().getInt(path, defaultData): defaultData; if(value < min) { value = min; } else if(value > max) { value = max; } return value; } private int getInt(String path, int defaultData, int min, int max) { return getInt(path, defaultData, min, max, true); } private boolean getBoolean(String path, boolean defaultData, boolean withSave) { if (getConfig().get(path) == null) { if(!withSave) { return defaultData; } getConfig().set(path, defaultData); } return getConfig().getBoolean(path, defaultData); } private boolean getBoolean(String path, boolean defaultData) { return getBoolean(path, defaultData, true); } private byte[] generateTransparentBlocks(int engineMode) { byte[] transparentBlocks = new byte[MaterialHelper.getMaxId() + 1]; Material[] allMaterials = Material.values(); for(Material material : allMaterials) { if(material.isBlock()) { boolean isTransparent = DeprecatedMethods.isTransparent(material); if(isTransparent) { Set<Integer> ids = NmsInstance.current.getMaterialIds(material); for (int id : ids) { transparentBlocks[id] = 1; } } } } Material[] extraTransparentBlocks = NmsInstance.current.getExtraTransparentBlocks(); for(Material material : extraTransparentBlocks) { Set<Integer> ids = NmsInstance.current.getMaterialIds(material); for (int id : ids) { transparentBlocks[id] = 1; } } Set<Integer> lavaIds = NmsInstance.current.getMaterialIds(Material.LAVA); for (int id : lavaIds) { transparentBlocks[id] = (byte)(engineMode == 1 ? 0 : 1); } return transparentBlocks; } }
10,446
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
WorldReader.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/config/WorldReader.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.config; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import com.lishid.orebfuscator.NmsInstance; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.java.JavaPlugin; import com.lishid.orebfuscator.utils.Globals; public class WorldReader { private enum WorldType { Default, Normal, TheEnd, Nether } private WorldConfig defaultWorld; private WorldConfig normalWorld; private WorldConfig endWorld; private WorldConfig netherWorld; private Map<String, WorldConfig> worlds; private JavaPlugin plugin; private Logger logger; private OrebfuscatorConfig orebfuscatorConfig; private MaterialReader materialReader; public WorldReader( JavaPlugin plugin, Logger logger, OrebfuscatorConfig orebfuscatorConfig, MaterialReader materialReader ) { this.plugin = plugin; this.logger = logger; this.orebfuscatorConfig = orebfuscatorConfig; this.materialReader = materialReader; } public void load() { ConfigurationSection section = getConfig().getConfigurationSection("Worlds"); Set<String> keys = section != null ? section.getKeys(false): new HashSet<String>(); this.defaultWorld = readWorldByType(keys, WorldType.Default, null); this.normalWorld = readWorldByType(keys, WorldType.Normal, this.defaultWorld); this.endWorld = readWorldByType(keys, WorldType.TheEnd, this.defaultWorld); this.netherWorld = readWorldByType(keys, WorldType.Nether, this.defaultWorld); this.worlds = new HashMap<String, WorldConfig>(); for(String key : keys) { readWorldsByName("Worlds." + key); } this.orebfuscatorConfig.setDefaultWorld(this.defaultWorld); this.orebfuscatorConfig.setNormalWorld(this.normalWorld); this.orebfuscatorConfig.setEndWorld(this.endWorld); this.orebfuscatorConfig.setNetherWorld(this.netherWorld); this.orebfuscatorConfig.setWorlds(this.worlds); } private FileConfiguration getConfig() { return this.plugin.getConfig(); } public static String createPath(String path, String key, FileConfiguration config) { int counter = 1; String newPath = path + "." + key; while(config.get(newPath) != null) { newPath = path + "." + key + (counter++); } return newPath; } private WorldConfig readWorldByType(Set<String> keys, WorldType worldType, WorldConfig baseWorld) { WorldConfig world = null; for(String key : keys) { String worldPath = "Worlds." + key; List<String> types = getStringList(worldPath + ".Types", null, false); if(types != null && types.size() > 0 && parseWorldTypes(types).contains(worldType)) { if(worldType == WorldType.Default) { world = new WorldConfig(); world.setDefaults(); } world = readWorld(worldPath, world, worldType, worldType == WorldType.Default); this.logger.log(Level.INFO, Globals.LogPrefix + "World type '" + worldType + "' has been read."); break; } } if(world == null) { switch(worldType) { case Default: world = createDefaultWorld(createPath("Worlds", "Default", getConfig())); break; case Normal: world = createNormalWorld(createPath("Worlds", "Normal", getConfig())); break; case TheEnd: world = createEndWorld(createPath("Worlds", "TheEnd", getConfig())); break; case Nether: world = createNetherWorld(createPath("Worlds", "Nether", getConfig())); break; } this.logger.log(Level.WARNING, Globals.LogPrefix + "World type '" + worldType + "' has been created."); } world.init(baseWorld); return world; } private void readWorldsByName(String worldPath) { List<String> names = getStringList(worldPath + ".Names", null, false); if(names == null || names.size() == 0) { return; } for(String name : names) { String key = name.toLowerCase(); if(!this.worlds.containsKey(key)) { WorldConfig world = readWorld(worldPath, null, WorldType.Default, false); world.setName(name); this.worlds.put(key, world); this.logger.log(Level.INFO, Globals.LogPrefix + "World name '" + name + "' has been read."); } } } private List<WorldType> parseWorldTypes(List<String> types) { List<WorldType> parsedTypes = new ArrayList<WorldType>(); for(String type : types) { WorldType worldType; if(type.equalsIgnoreCase("DEFAULT")) { worldType = WorldType.Default; } else if(type.equalsIgnoreCase("NORMAL")) { worldType = WorldType.Normal; } else if(type.equalsIgnoreCase("THE_END")) { worldType = WorldType.TheEnd; } else if(type.equalsIgnoreCase("NETHER")) { worldType = WorldType.Nether; } else { this.logger.log(Level.WARNING, Globals.LogPrefix + "World type '" + type + "' is not supported."); continue; } parsedTypes.add(worldType); } return parsedTypes; } private WorldConfig readWorld(String worldPath, WorldConfig cfg, WorldType worldType, boolean withSave) { if(cfg == null) { cfg = new WorldConfig(); } Boolean enabled = getBoolean(worldPath + ".Enabled", cfg.isEnabled(), withSave); Boolean antiTexturePackAndFreecam = getBoolean(worldPath + ".AntiTexturePackAndFreecam", cfg.isAntiTexturePackAndFreecam(), withSave); Integer airGeneratorMaxChance = getInt(worldPath + ".AirGeneratorMaxChance", cfg.getAirGeneratorMaxChance(), 40, 100, withSave); Boolean darknessHideBlocks = getBoolean(worldPath + ".DarknessHideBlocks", cfg.isDarknessHideBlocks(), withSave); Boolean bypassObfuscationForSignsWithText = getBoolean(worldPath + ".BypassObfuscationForSignsWithText", cfg.isBypassObfuscationForSignsWithText(), withSave); HashSet<Integer> darknessBlocks = readBlockMatrix(cfg.getDarknessBlocks(), worldPath + ".DarknessBlocks", withSave); Integer mode1Block = this.materialReader.getMaterialIdByPath(worldPath + ".Mode1Block", cfg.getMode1BlockId(), withSave); Integer[] randomBlocks = this.materialReader.getMaterialIdsByPath(worldPath + ".RandomBlocks", cfg.getRandomBlocks(), withSave); HashSet<Integer> obfuscateBlocks = readBlockMatrix(cfg.getObfuscateBlocks(), worldPath + ".ObfuscateBlocks", withSave); int[] requiredObfuscateBlockIds; switch(worldType) { case Normal: requiredObfuscateBlockIds = NmsInstance.current.getConfigDefaults().normalWorldRequiredObfuscateBlockIds; break; case TheEnd: requiredObfuscateBlockIds = NmsInstance.current.getConfigDefaults().endWorldRequiredObfuscateBlockIds; break; case Nether: requiredObfuscateBlockIds = NmsInstance.current.getConfigDefaults().netherWorldRequiredObfuscateBlockIds; break; default: requiredObfuscateBlockIds = null; break; } if(requiredObfuscateBlockIds != null) { for (int blockId : requiredObfuscateBlockIds) { obfuscateBlocks.add(blockId); } } readProximityHider(worldPath, cfg, withSave); cfg.setEnabled(enabled); cfg.setAntiTexturePackAndFreecam(antiTexturePackAndFreecam); cfg.setBypassObfuscationForSignsWithText(bypassObfuscationForSignsWithText); cfg.setAirGeneratorMaxChance(airGeneratorMaxChance); cfg.setDarknessHideBlocks(darknessHideBlocks); cfg.setDarknessBlocks(darknessBlocks); cfg.setMode1BlockId(mode1Block); cfg.setRandomBlocks(randomBlocks); cfg.setObfuscateBlocks(obfuscateBlocks); return cfg; } private void readProximityHider(String worldPath, WorldConfig worldConfig, boolean withSave) { ProximityHiderConfig cfg = worldConfig.getProximityHiderConfig(); Integer[] defaultProximityHiderBlockIds = cfg.getProximityHiderBlocks() != null ? cfg.getProximityHiderBlocks().toArray(new Integer[0]) : null; String sectionPath = worldPath + ".ProximityHider"; Boolean enabled = getBoolean(sectionPath + ".Enabled", cfg.isEnabled(), withSave); Integer distance = getInt(sectionPath + ".Distance", cfg.getDistance(), 2, 64, withSave); Integer specialBlockID = this.materialReader.getMaterialIdByPath(sectionPath + ".SpecialBlock", cfg.getSpecialBlockID(), withSave); Integer y = getInt(sectionPath + ".Y", cfg.getY(), 0, 255, withSave); Boolean useSpecialBlock = getBoolean(sectionPath + ".UseSpecialBlock", cfg.isUseSpecialBlock(), withSave); Boolean useYLocationProximity = getBoolean(sectionPath + ".ObfuscateAboveY", cfg.isObfuscateAboveY(), withSave); Integer[] proximityHiderBlockIds = this.materialReader.getMaterialIdsByPath(sectionPath + ".ProximityHiderBlocks", defaultProximityHiderBlockIds, withSave); ProximityHiderConfig.BlockSetting[] proximityHiderBlockSettings = readProximityHiderBlockSettings(sectionPath + ".ProximityHiderBlockSettings", cfg.getProximityHiderBlockSettings()); Boolean useFastGazeCheck = getBoolean(sectionPath + ".UseFastGazeCheck", cfg.isUseFastGazeCheck(), withSave); cfg.setEnabled(enabled); cfg.setDistance(distance); cfg.setSpecialBlockID(specialBlockID); cfg.setY(y); cfg.setUseSpecialBlock(useSpecialBlock); cfg.setObfuscateAboveY(useYLocationProximity); cfg.setProximityHiderBlocks(proximityHiderBlockIds); cfg.setProximityHiderBlockSettings(proximityHiderBlockSettings); cfg.setUseFastGazeCheck(useFastGazeCheck); } private ProximityHiderConfig.BlockSetting[] readProximityHiderBlockSettings( String configKey, ProximityHiderConfig.BlockSetting[] defaultBlocks ) { ConfigurationSection section = getConfig().getConfigurationSection(configKey); if(section == null) { return defaultBlocks; } Set<String> keys = section.getKeys(false); List<ProximityHiderConfig.BlockSetting> list = new ArrayList<ProximityHiderConfig.BlockSetting>(); for(String key : keys) { Set<Integer> blockIds = this.materialReader.getMaterialIds(key); if(blockIds == null) { continue; } String blockPath = configKey + "." + key; int blockY = getConfig().getInt(blockPath + ".Y", 255); boolean blockObfuscateAboveY = getConfig().getBoolean(blockPath + ".ObfuscateAboveY", false); for(int blockId : blockIds) { ProximityHiderConfig.BlockSetting block = new ProximityHiderConfig.BlockSetting(); block.blockId = blockId; block.y = blockY; block.obfuscateAboveY = blockObfuscateAboveY; list.add(block); } } return list.toArray(new ProximityHiderConfig.BlockSetting[0]); } private HashSet<Integer> readBlockMatrix(HashSet<Integer> original, String configKey, boolean withSave) { Integer[] defaultBlockIds; if(original != null && original.size() != 0) { defaultBlockIds = new Integer[original.size()]; int index = 0; for(Integer id : original) { defaultBlockIds[index++] = id; } } else { defaultBlockIds = null; } Integer[] blockIds = this.materialReader.getMaterialIdsByPath(configKey, defaultBlockIds, withSave); HashSet<Integer> blocks; if(blockIds != null) { blocks = new HashSet<>(); for(int id : blockIds) { blocks.add(id); } } else { blocks = original; } return blocks; } private WorldConfig createDefaultWorld(String worldPath) { getConfig().set(worldPath + ".Types", new String[] { "DEFAULT" }); WorldConfig world = new WorldConfig(); world.setDefaults(); return readWorld(worldPath, world, WorldType.Default, true); } private WorldConfig createNormalWorld(String worldPath) { Integer[] randomBlocks = cloneIntArray(NmsInstance.current.getConfigDefaults().normalWorldRandomBlockIds); Integer[] obfuscateBlockIds = mergeIntArrays(NmsInstance.current.getConfigDefaults().normalWorldObfuscateBlockIds, NmsInstance.current.getConfigDefaults().normalWorldRequiredObfuscateBlockIds); getConfig().set(worldPath + ".Types", new String[] { "NORMAL" }); int mode1BlockId = NmsInstance.current.getConfigDefaults().normalWorldMode1BlockId; this.materialReader.getMaterialIdByPath(worldPath + ".Mode1Block", mode1BlockId, true); this.materialReader.getMaterialIdsByPath(worldPath + ".RandomBlocks", randomBlocks, true); this.materialReader.getMaterialIdsByPath(worldPath + ".ObfuscateBlocks", obfuscateBlockIds, true); WorldConfig cfg = new WorldConfig(); cfg.setObfuscateBlocks(obfuscateBlockIds); cfg.setRandomBlocks(randomBlocks); cfg.setMode1BlockId(mode1BlockId); return cfg; } private WorldConfig createEndWorld(String worldPath) { Integer[] randomBlocks = cloneIntArray(NmsInstance.current.getConfigDefaults().endWorldRandomBlockIds); Integer[] obfuscateBlockIds = mergeIntArrays(NmsInstance.current.getConfigDefaults().endWorldObfuscateBlockIds, NmsInstance.current.getConfigDefaults().endWorldRequiredObfuscateBlockIds); getConfig().set(worldPath + ".Types", new String[] { "THE_END" }); int mode1BlockId = NmsInstance.current.getConfigDefaults().endWorldMode1BlockId; this.materialReader.getMaterialIdByPath(worldPath + ".Mode1Block", mode1BlockId, true); this.materialReader.getMaterialIdsByPath(worldPath + ".RandomBlocks", randomBlocks, true); this.materialReader.getMaterialIdsByPath(worldPath + ".ObfuscateBlocks", obfuscateBlockIds, true); WorldConfig cfg = new WorldConfig(); cfg.setRandomBlocks(randomBlocks); cfg.setObfuscateBlocks(obfuscateBlockIds); cfg.setMode1BlockId(mode1BlockId); return cfg; } private WorldConfig createNetherWorld(String worldPath) { Integer[] randomBlocks = cloneIntArray(NmsInstance.current.getConfigDefaults().netherWorldRandomBlockIds); Integer[] obfuscateBlockIds = mergeIntArrays(NmsInstance.current.getConfigDefaults().netherWorldObfuscateBlockIds, NmsInstance.current.getConfigDefaults().netherWorldRequiredObfuscateBlockIds); getConfig().set(worldPath + ".Types", new String[] { "NETHER" }); int mode1BlockId = NmsInstance.current.getConfigDefaults().netherWorldMode1BlockId; this.materialReader.getMaterialIdByPath(worldPath + ".Mode1Block", mode1BlockId, true); this.materialReader.getMaterialIdsByPath(worldPath + ".RandomBlocks", randomBlocks, true); this.materialReader.getMaterialIdsByPath(worldPath + ".ObfuscateBlocks", obfuscateBlockIds, true); WorldConfig cfg = new WorldConfig(); cfg.setRandomBlocks(randomBlocks); cfg.setObfuscateBlocks(obfuscateBlockIds); cfg.setMode1BlockId(mode1BlockId); return cfg; } private Integer getInt(String path, Integer defaultData, int min, int max, boolean withSave) { if (getConfig().get(path) == null && withSave) { getConfig().set(path, defaultData); } Integer value = getConfig().get(path) != null ? (Integer)getConfig().getInt(path): defaultData; if(value != null) { if(value < min) { value = min; } else if(value > max) { value = max; } } return value; } private Boolean getBoolean(String path, Boolean defaultData, boolean withSave) { if (getConfig().get(path) == null) { if(!withSave) { return defaultData; } getConfig().set(path, defaultData); } return getConfig().get(path) != null ? (Boolean)getConfig().getBoolean(path): defaultData; } private List<String> getStringList(String path, List<String> defaultData, boolean withSave) { if (getConfig().get(path) == null) { if(!withSave) { return defaultData; } getConfig().set(path, defaultData); } return getConfig().getStringList(path); } private static Integer[] cloneIntArray(int[] array) { Integer[] result = new Integer[array.length]; for(int i = 0; i < array.length; i++) { result[i] = array[i]; } return result; } private static Integer[] mergeIntArrays(int[] array1, int[] array2) { Integer[] result = new Integer[array1.length + array2.length]; for(int i = 0; i < array1.length; i++) { result[i] = array1[i]; } for(int i = 0; i < array2.length; i++) { result[array1.length + i] = array2[i]; } return result; } }
16,624
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ProximityHiderConfig.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/config/ProximityHiderConfig.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.config; import com.lishid.orebfuscator.NmsInstance; import com.lishid.orebfuscator.utils.MaterialHelper; import java.util.HashSet; public class ProximityHiderConfig { public static class BlockSetting implements Cloneable { public int blockId; public int y; public boolean obfuscateAboveY; public BlockSetting clone() throws CloneNotSupportedException { BlockSetting clone = new BlockSetting(); clone.blockId = this.blockId; clone.y = this.y; clone.obfuscateAboveY = this.obfuscateAboveY; return clone; } } private Boolean enabled; private Integer distance; private int distanceSquared; private Integer specialBlockID; private Integer y; private Boolean useSpecialBlock; private Boolean obfuscateAboveY; private Boolean useFastGazeCheck; private HashSet<Integer> proximityHiderBlocks; private BlockSetting[] proximityHiderBlockSettings; private short[] proximityHiderBlocksAndY; public void setDefaults() { this.enabled = true; this.distance = 8; this.distanceSquared = this.distance * this.distance; this.specialBlockID = NmsInstance.current.getConfigDefaults().defaultProximityHiderSpecialBlockId; this.y = 255; this.useSpecialBlock = true; this.obfuscateAboveY = false; this.useFastGazeCheck = true; this.proximityHiderBlocks = new HashSet<>(); for(int blockId : NmsInstance.current.getConfigDefaults().defaultProximityHiderBlockIds) { this.proximityHiderBlocks.add(blockId); } } public void init(ProximityHiderConfig baseCfg) { if(this.enabled == null) { this.enabled = baseCfg.enabled; } if(this.distance == null) { this.distance = baseCfg.distance; this.distanceSquared = baseCfg.distanceSquared; } if(this.specialBlockID == null) { this.specialBlockID = baseCfg.specialBlockID; } if(this.y == null) { this.y = baseCfg.y; } if(this.useSpecialBlock == null) { this.useSpecialBlock = baseCfg.useSpecialBlock; } if(this.obfuscateAboveY == null) { this.obfuscateAboveY = baseCfg.obfuscateAboveY; } if(this.proximityHiderBlocks == null && baseCfg.proximityHiderBlocks != null) { this.proximityHiderBlocks = new HashSet<>(); this.proximityHiderBlocks.addAll(baseCfg.proximityHiderBlocks); } if(this.proximityHiderBlockSettings == null && baseCfg.proximityHiderBlockSettings != null) { this.proximityHiderBlockSettings = baseCfg.proximityHiderBlockSettings.clone(); } if (this.useFastGazeCheck == null) { this.useFastGazeCheck = baseCfg.useFastGazeCheck; } setProximityHiderBlockMatrix(); } public Boolean isEnabled() { return this.enabled; } public void setEnabled(Boolean value) { this.enabled = value; } public Integer getDistance() { return this.distance; } public void setDistance(Integer value) { this.distance = value; this.distanceSquared = this.distance != null ? this.distance * this.distance: 0; } public int getDistanceSquared() { return this.distanceSquared; } public Integer getSpecialBlockID() { return this.specialBlockID; } public void setSpecialBlockID(Integer value) { this.specialBlockID = value; } public Integer getY() { return this.y; } public void setY(Integer value) { this.y = value; } public Boolean isUseSpecialBlock() { return this.useSpecialBlock; } public void setUseSpecialBlock(Boolean value) { this.useSpecialBlock = value; } public Boolean isObfuscateAboveY() { return this.obfuscateAboveY; } public void setObfuscateAboveY(Boolean value) { this.obfuscateAboveY = value; } public void setProximityHiderBlocks(Integer[] blockIds) { if(blockIds != null) { this.proximityHiderBlocks = new HashSet<>(); for (Integer id : blockIds) { this.proximityHiderBlocks.add(id); } } } public HashSet<Integer> getProximityHiderBlocks() { return this.proximityHiderBlocks; } public BlockSetting[] getProximityHiderBlockSettings() { return this.proximityHiderBlockSettings; } public void setProximityHiderBlockSettings(BlockSetting[] value) { this.proximityHiderBlockSettings = value; } private void setProximityHiderBlockMatrix() { this.proximityHiderBlocksAndY = new short[MaterialHelper.getMaxId() + 1]; if(this.proximityHiderBlocks == null) { return; } for(int blockId : this.proximityHiderBlocks) { this.proximityHiderBlocksAndY[blockId] = (short)(this.obfuscateAboveY ? -this.y: this.y); } if(this.proximityHiderBlockSettings != null) { for(BlockSetting block : this.proximityHiderBlockSettings) { this.proximityHiderBlocksAndY[block.blockId] = (short)(block.obfuscateAboveY ? -block.y: block.y); } } } public Boolean isUseFastGazeCheck() { return this.useFastGazeCheck; } public void setUseFastGazeCheck(Boolean value) { this.useFastGazeCheck = value; } // Help methods public boolean isProximityObfuscated(int y, int id) { int proximityY = this.proximityHiderBlocksAndY[id]; if(proximityY > 0) { return y <= proximityY; } return y >= (proximityY & 0xFFF); } }
5,821
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
Convert12To13.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/config/Convert12To13.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.config; import java.util.List; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.java.JavaPlugin; public class Convert12To13 { private static final int CONFIG_VERSION = 13; private JavaPlugin plugin; private FileConfiguration config; public Convert12To13(JavaPlugin plugin) { this.plugin = plugin; } public void convert() { this.config = new YamlConfiguration(); setGlobalValues(); setWorldValues(); String contents = this.config.saveToString(); try { this.plugin.getConfig().loadFromString(contents); } catch (InvalidConfigurationException e) { e.printStackTrace(); } } private void setGlobalValues() { FileConfiguration oldConfig = this.plugin.getConfig(); this.config.set("ConfigVersion", CONFIG_VERSION); this.config.set("Booleans.UseCache", oldConfig.get("Booleans.UseCache")); this.config.set("Booleans.Enabled", oldConfig.get("Booleans.Enabled")); this.config.set("Booleans.UpdateOnDamage", oldConfig.get("Booleans.UpdateOnDamage")); this.config.set("Booleans.NoObfuscationForMetadata", oldConfig.get("Booleans.NoObfuscationForMetadata")); this.config.set("Booleans.NoObfuscationForOps", oldConfig.get("Booleans.NoObfuscationForOps")); this.config.set("Booleans.NoObfuscationForPermission", oldConfig.get("Booleans.NoObfuscationForPermission")); this.config.set("Booleans.LoginNotification", oldConfig.get("Booleans.LoginNotification")); this.config.set("Integers.MaxLoadedCacheFiles", oldConfig.get("Integers.MaxLoadedCacheFiles")); this.config.set("Integers.DeleteCacheFilesAfterDays", oldConfig.get("Integers.DeleteCacheFilesAfterDays")); this.config.set("Integers.EngineMode", oldConfig.get("Integers.EngineMode")); this.config.set("Integers.InitialRadius", oldConfig.get("Integers.InitialRadius")); this.config.set("Integers.UpdateRadius", oldConfig.get("Integers.UpdateRadius")); this.config.set("Strings.CacheLocation", oldConfig.get("Strings.CacheLocation")); this.config.set("Strings.NoObfuscationForMetadataTagName", oldConfig.get("Strings.NoObfuscationForMetadataTagName")); this.config.set("Lists.TransparentBlocks", oldConfig.get("Lists.TransparentBlocks")); this.config.set("Lists.NonTransparentBlocks", oldConfig.get("Lists.NonTransparentBlocks")); } private void setWorldValues() { FileConfiguration oldConfig = this.plugin.getConfig(); boolean worldEnabled = oldConfig.get("Booleans.UseWorldsAsBlacklist") == null || oldConfig.getBoolean("Booleans.UseWorldsAsBlacklist"); // Default World this.config.set("Worlds.Default.Types", new String[] { "DEFAULT" }); this.config.set("Worlds.Default.Enabled", worldEnabled); this.config.set("Worlds.Default.AntiTexturePackAndFreecam", oldConfig.get("Booleans.AntiTexturePackAndFreecam")); this.config.set("Worlds.Default.AirGeneratorMaxChance", oldConfig.get("Integers.AirGeneratorMaxChance")); this.config.set("Worlds.Default.DarknessHideBlocks", oldConfig.get("Booleans.DarknessHideBlocks")); this.config.set("Worlds.Default.DarknessBlocks", oldConfig.get("Lists.DarknessBlocks")); this.config.set("Worlds.Default.Mode1Block", 1); this.config.set("Worlds.Default.ProximityHider.Enabled", oldConfig.get("Booleans.UseProximityHider")); this.config.set("Worlds.Default.ProximityHider.Distance", oldConfig.get("Integers.ProximityHiderDistance")); this.config.set("Worlds.Default.ProximityHider.SpecialBlock", oldConfig.get("Integers.ProximityHiderID")); this.config.set("Worlds.Default.ProximityHider.Y", oldConfig.get("Integers.ProximityHiderEnd")); this.config.set("Worlds.Default.ProximityHider.UseSpecialBlock", oldConfig.get("Booleans.UseSpecialBlockForProximityHider")); this.config.set("Worlds.Default.ProximityHider.ObfuscateAboveY", oldConfig.get("Booleans.UseYLocationProximity")); this.config.set("Worlds.Default.ProximityHider.ProximityHiderBlocks", oldConfig.get("Lists.ProximityHiderBlocks")); //Normal and TheEnd Worlds this.config.set("Worlds.Normal.Types", new String[] { "NORMAL", "THE_END" }); this.config.set("Worlds.Normal.Mode1Block", 1); this.config.set("Worlds.Normal.RandomBlocks", oldConfig.get("Lists.RandomBlocks")); this.config.set("Worlds.Normal.ObfuscateBlocks", oldConfig.get("Lists.ObfuscateBlocks")); //Nether World this.config.set("Worlds.Nether.Types", new String[] { "NETHER" }); this.config.set("Worlds.Nether.Mode1Block", 87); this.config.set("Worlds.Nether.RandomBlocks", oldConfig.get("Lists.NetherRandomBlocks")); this.config.set("Worlds.Nether.ObfuscateBlocks", oldConfig.get("Lists.NetherObfuscateBlocks")); List<String> worldNames = oldConfig.getStringList("Lists.Worlds"); if(worldNames == null) { worldNames = oldConfig.getStringList("Lists.DisabledWorlds"); } if(worldNames != null && worldNames.size() > 0) { this.config.set("Worlds.CustomWorld.Names", worldNames); this.config.set("Worlds.CustomWorld.Enabled", !worldEnabled); } } }
5,402
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkData.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/chunkmap/ChunkData.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.chunkmap; import java.util.List; import com.comphenix.protocol.wrappers.nbt.NbtCompound; public class ChunkData { public int chunkX; public int chunkZ; public boolean groundUpContinuous; public int primaryBitMask; public byte[] data; public boolean isOverworld; public boolean useCache; public List<NbtCompound> blockEntities; }
409
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkWriter.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/chunkmap/ChunkWriter.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.chunkmap; import java.io.IOException; public class ChunkWriter { private byte[] data; private int bitsPerBlock; private int byteIndex; private int bitIndex; private long buffer; public ChunkWriter(byte[] data) { this.data = data; } public int getByteIndex() { return this.byteIndex; } public void init() { this.byteIndex = 0; this.bitIndex = 0; this.buffer = 0; } public void setBitsPerBlock(int bitsPerBlock) { this.bitsPerBlock = bitsPerBlock; } public void save() throws IOException { writeLong(); } public void skip(int count) { this.byteIndex += count; this.bitIndex = 0; } public void writeBytes(byte[] source, int index, int length) throws IOException { if(this.byteIndex + length > this.data.length) { throw new IOException("No space to write."); } System.arraycopy(source, index, this.data, this.byteIndex, length); this.byteIndex += length; } public void writeBlockBits(long bits) throws IOException { if(this.bitIndex >= 64) { writeLong(); this.bitIndex = 0; } int leftBits = 64 - this.bitIndex; this.buffer |= bits << this.bitIndex; if(leftBits >= this.bitsPerBlock) { this.bitIndex += this.bitsPerBlock; } else { writeLong(); this.buffer = bits >>> leftBits; this.bitIndex = this.bitsPerBlock - leftBits; } } private void writeLong() throws IOException { if(this.byteIndex + 7 >= this.data.length) { throw new IOException("No space to write."); } this.data[this.byteIndex++] = (byte)(this.buffer >> 56); this.data[this.byteIndex++] = (byte)(this.buffer >> 48); this.data[this.byteIndex++] = (byte)(this.buffer >> 40); this.data[this.byteIndex++] = (byte)(this.buffer >> 32); this.data[this.byteIndex++] = (byte)(this.buffer >> 24); this.data[this.byteIndex++] = (byte)(this.buffer >> 16); this.data[this.byteIndex++] = (byte)(this.buffer >> 8); this.data[this.byteIndex++] = (byte)this.buffer; this.buffer = 0; } public void writeVarInt(int value) throws IOException { while((value & ~0x7F) != 0) { writeByte((value & 0x7F) | 0x80); value >>>= 7; } writeByte(value); } public void writeByte(int value) throws IOException { if(this.byteIndex >= this.data.length) { throw new IOException("No space to write."); } this.data[this.byteIndex++] = (byte)value; } }
2,465
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkMapBuffer.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/chunkmap/ChunkMapBuffer.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.chunkmap; public class ChunkMapBuffer { private static int _bitsPerBlock; public static int getBitsPerBlock() { return _bitsPerBlock; } private static final int BITS_PER_BLOCK_SIZE = 1; private static final int PALETTE_LENGTH_SIZE = 5; private static final int DATA_ARRAY_LENGTH_SIZE = 5; private static final int BLOCKS_PER_CHUNK_SECTION = 16 * 16 * 16; private static final int BLOCK_LIGHT_SIZE = BLOCKS_PER_CHUNK_SECTION / 2; private static final int SKY_LIGHT_SIZE = BLOCKS_PER_CHUNK_SECTION / 2; private static final int COLUMNS_PER_CHUNK = 16; private static int MAX_BYTES_PER_CHUNK; public static void init(int bitsPerBlock) { _bitsPerBlock = bitsPerBlock; int dataArraySize = BLOCKS_PER_CHUNK_SECTION * _bitsPerBlock / 8; MAX_BYTES_PER_CHUNK = COLUMNS_PER_CHUNK * ( BITS_PER_BLOCK_SIZE + PALETTE_LENGTH_SIZE + DATA_ARRAY_LENGTH_SIZE + dataArraySize + BLOCK_LIGHT_SIZE + SKY_LIGHT_SIZE ); } public int[] palette; public byte[] output; public int[] outputPalette; public byte[] outputPaletteMap; public ChunkWriter writer; public ChunkLayer prevLayer; public ChunkLayer curLayer; public ChunkLayer nextLayer; public int bitsPerBlock; public int paletteLength; public int dataArrayLength; public int lightArrayLength; public int dataArrayStartIndex; public int outputPaletteLength; public int outputBitsPerBlock; public ChunkMapBuffer() { this.palette = new int[256]; this.output = new byte[MAX_BYTES_PER_CHUNK]; this.outputPalette = new int[256]; this.outputPaletteMap = new byte[65536]; this.writer = new ChunkWriter(this.output); this.prevLayer = new ChunkLayer(); this.prevLayer.map = new int[16 * 16]; this.curLayer = new ChunkLayer(); this.curLayer.map = new int[16 * 16]; this.nextLayer = new ChunkLayer(); this.nextLayer.map = new int[16 * 16]; } public void clearLayers() { this.prevLayer.hasData = false; this.curLayer.hasData = false; this.nextLayer.hasData = false; } }
2,113
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkLayer.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/chunkmap/ChunkLayer.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.chunkmap; public class ChunkLayer { public boolean hasData; public int[] map; }
152
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkMapManager.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/chunkmap/ChunkMapManager.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.chunkmap; import java.io.IOException; import java.util.Arrays; import java.util.Stack; import com.lishid.orebfuscator.NmsInstance; public class ChunkMapManager implements AutoCloseable { private static final Object _lock = new Object(); private static final Stack<ChunkMapBuffer> _bufferStack = new Stack<>(); private static ChunkMapBuffer popBuffer() { synchronized(_lock) { return _bufferStack.isEmpty() ? new ChunkMapBuffer() : _bufferStack.pop(); } } private static void pushBuffer(ChunkMapBuffer buffer) { synchronized(_lock) { _bufferStack.push(buffer); } } private ChunkMapBuffer buffer; private ChunkData chunkData; private ChunkReader reader; private int sectionCount; private int sectionIndex; private int y; private int minX; private int maxX; private int minZ; private int maxZ; private int blockIndex; public int getSectionCount() { return this.sectionCount; } public int getY() { return this.y; } public ChunkData getChunkData() { return this.chunkData; } private ChunkMapManager() { } public static ChunkMapManager create(ChunkData chunkData) throws IOException { ChunkMapManager manager = new ChunkMapManager(); manager.chunkData = chunkData; manager.buffer = popBuffer(); manager.reader = new ChunkReader(chunkData.data); manager.sectionCount = 0; manager.sectionIndex = -1; manager.minX = chunkData.chunkX << 4; manager.maxX = manager.minX + 15; manager.minZ = chunkData.chunkZ << 4; manager.maxZ = manager.minZ + 15; manager.buffer.lightArrayLength = 2048; if(chunkData.isOverworld) { manager.buffer.lightArrayLength <<= 1; } manager.buffer.writer.init(); int mask = chunkData.primaryBitMask; while(mask != 0) { if((mask & 0x1) != 0) { manager.sectionCount++; } mask >>>= 1; } manager.buffer.clearLayers(); manager.moveToNextLayer(); return manager; } public void close() throws Exception { pushBuffer(this.buffer); } public boolean inputHasNonAirBlock() { return this.buffer.paletteLength > 1 || NmsInstance.current.isAir(this.buffer.palette[0]); } public boolean initOutputPalette() { if(this.buffer.paletteLength == 0 || this.buffer.paletteLength == 255) { this.buffer.outputPaletteLength = 0; return false; } Arrays.fill(this.buffer.outputPaletteMap, (byte)-1); this.buffer.outputPaletteLength = this.buffer.paletteLength; for(int i = 0; i < this.buffer.paletteLength; i++) { int blockData = this.buffer.palette[i]; this.buffer.outputPalette[i] = blockData; if(blockData >= 0) { this.buffer.outputPaletteMap[blockData] = (byte)i; } } return true; } public boolean addToOutputPalette(int blockData) { if(this.buffer.outputPaletteMap[blockData] >= 0) return true; //255 (-1 for byte) is special code in my algorithm if(this.buffer.outputPaletteLength == 254) { this.buffer.outputPaletteLength = 0; return false; } this.buffer.outputPalette[this.buffer.outputPaletteLength] = blockData; this.buffer.outputPaletteMap[blockData] = (byte)this.buffer.outputPaletteLength; this.buffer.outputPaletteLength++; return true; } public void initOutputSection() throws IOException { calcOutputBitsPerBlock(); this.buffer.writer.setBitsPerBlock(this.buffer.outputBitsPerBlock); //Bits Per Block this.buffer.writer.writeByte((byte)this.buffer.outputBitsPerBlock); //Palette Length this.buffer.writer.writeVarInt(this.buffer.outputPaletteLength); //Palette for(int i = 0; i < this.buffer.outputPaletteLength; i++) { this.buffer.writer.writeVarInt(this.buffer.outputPalette[i]); } int dataArrayLengthInBits = this.buffer.outputBitsPerBlock << 12;// multiply by 4096 int outputDataArrayLength = dataArrayLengthInBits >>> 6;//divide by 64 if((dataArrayLengthInBits & 0x3f) != 0) { outputDataArrayLength++; } //Data Array Length this.buffer.writer.writeVarInt(outputDataArrayLength); //Copy Block Light and Sky Light arrays int lightArrayStartIndex = this.buffer.dataArrayStartIndex + (this.buffer.dataArrayLength << 3); int outputLightArrayStartIndex = this.buffer.writer.getByteIndex() + (outputDataArrayLength << 3); System.arraycopy( this.chunkData.data, lightArrayStartIndex, this.buffer.output, outputLightArrayStartIndex, this.buffer.lightArrayLength ); } public void writeOutputBlock(int blockData) throws IOException { if(this.buffer.outputPaletteLength > 0) { long paletteIndex = this.buffer.outputPaletteMap[blockData] & 0xffL; if(paletteIndex == 255) { throw new IllegalArgumentException("Block " + blockData + " is absent in output palette."); } this.buffer.writer.writeBlockBits(paletteIndex); } else { this.buffer.writer.writeBlockBits(blockData); } } public void finalizeOutput() throws IOException { if(this.buffer.writer.getByteIndex() == 0) return; this.buffer.writer.save(); this.buffer.writer.skip(this.buffer.lightArrayLength); } public byte[] createOutput() { int readerByteIndex = this.reader.getByteIndex(); int writerByteIndex = this.buffer.writer.getByteIndex(); int biomesSize = this.chunkData.data.length - readerByteIndex; byte[] output = new byte[writerByteIndex + biomesSize]; System.arraycopy(this.buffer.output, 0, output, 0, writerByteIndex); if(biomesSize > 0) { System.arraycopy( this.chunkData.data, readerByteIndex, output, writerByteIndex, biomesSize ); } return output; } private void calcOutputBitsPerBlock() { if(this.buffer.outputPaletteLength == 0) { this.buffer.outputBitsPerBlock = ChunkMapBuffer.getBitsPerBlock(); } else { byte mask = (byte)this.buffer.outputPaletteLength; int index = 0; while((mask & 0x80) == 0) { index++; mask <<= 1; } this.buffer.outputBitsPerBlock = 8 - index; if(this.buffer.outputBitsPerBlock < 4) { this.buffer.outputBitsPerBlock = 4; } } } public int readNextBlock() throws IOException { if(this.blockIndex == 16 * 16) { if(!moveToNextLayer()) return -1; } return this.buffer.curLayer.map[this.blockIndex++]; } public int get(int x, int y, int z) throws IOException { if(x < minX || x > maxX || z < minZ || z > maxZ || y > 255 || y < this.y - 1 || y > this.y + 1 ) { return -1; } ChunkLayer layer; if(y == this.y) layer = this.buffer.curLayer; else if(y == this.y - 1) layer = this.buffer.prevLayer; else layer = this.buffer.nextLayer; if(!layer.hasData) return -1; int blockIndex = ((z - this.minZ) << 4) | (x - this.minX); return layer.map[blockIndex]; } private boolean moveToNextLayer() throws IOException { if(!increaseY()) return false; shiftLayersDown(); if(!this.buffer.curLayer.hasData) { readLayer(this.buffer.curLayer); } if(((this.y + 1) >>> 4) > this.sectionIndex) { int oldSectionIndex = this.sectionIndex; moveToNextSection(); if(this.sectionIndex < 16 && oldSectionIndex + 1 == this.sectionIndex) { readLayer(this.buffer.nextLayer); } } else { readLayer(this.buffer.nextLayer); } this.blockIndex = 0; return true; } private boolean increaseY() throws IOException { if(this.sectionIndex < 0) { if(!moveToNextSection()) return false; this.y = this.sectionIndex << 4; } else { this.y++; if((this.y & 0xf) == 0) { if(this.sectionIndex > 15) return false; if((this.y >>> 4) != this.sectionIndex) { this.buffer.clearLayers(); this.y = this.sectionIndex << 4; } } } return true; } private void shiftLayersDown() { ChunkLayer temp = this.buffer.prevLayer; this.buffer.prevLayer = this.buffer.curLayer; this.buffer.curLayer = this.buffer.nextLayer; this.buffer.nextLayer = temp; this.buffer.nextLayer.hasData = false; } private boolean moveToNextSection() throws IOException { if(this.sectionIndex >= 0) { this.reader.skip(this.buffer.lightArrayLength); } do { this.sectionIndex++; } while(this.sectionIndex < 16 && (this.chunkData.primaryBitMask & (1 << this.sectionIndex)) == 0); if(this.sectionIndex >= 16) return false; readSectionHeader(); return true; } private void readLayer(ChunkLayer layer) throws IOException { for(int i = 0; i < 16 * 16; i++) { int blockData = this.reader.readBlockBits(); if(this.buffer.paletteLength > 0) { blockData = blockData >= 0 && blockData < this.buffer.paletteLength ? this.buffer.palette[blockData] : NmsInstance.current.getCaveAirBlockId(); } layer.map[i] = blockData; } layer.hasData = true; } private void readSectionHeader() throws IOException { this.buffer.bitsPerBlock = this.reader.readByte(); this.buffer.paletteLength = this.reader.readVarInt(); for(int i = 0; i < this.buffer.paletteLength; i++) { int paletteData = this.reader.readVarInt(); this.buffer.palette[i] = paletteData; } this.buffer.dataArrayLength = this.reader.readVarInt(); this.buffer.dataArrayStartIndex = this.reader.getByteIndex(); this.reader.setBitsPerBlock(this.buffer.bitsPerBlock); } }
10,113
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkReader.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/chunkmap/ChunkReader.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.chunkmap; import java.io.IOException; public class ChunkReader { private byte[] data; private int bitsPerBlock; private long maxValueMask; private int byteIndex; private int bitIndex; private long buffer; public ChunkReader(byte[] data) { this.data = data; this.byteIndex = 0; this.bitIndex = 0; } public int getByteIndex() { return this.byteIndex; } public void skip(int count) { this.byteIndex += count; this.bitIndex = 0; } public void setBitsPerBlock(int bitsPerBlock) { this.bitsPerBlock = bitsPerBlock; this.maxValueMask = (1L << this.bitsPerBlock) - 1; } public int readBlockBits() throws IOException { if(this.bitIndex == 0 || this.bitIndex >= 64) { readLong(); this.bitIndex = 0; } int leftBits = 64 - this.bitIndex; long result = this.buffer >>> this.bitIndex; if(leftBits >= this.bitsPerBlock) { this.bitIndex += this.bitsPerBlock; } else { readLong(); result |= this.buffer << leftBits; this.bitIndex = this.bitsPerBlock - leftBits; } return (int)(result & this.maxValueMask); } private void readLong() throws IOException { if(this.byteIndex + 7 >= this.data.length) { throw new IOException("No data to read. byteIndex = " + this.byteIndex); } this.buffer = ((this.data[this.byteIndex] & 0xffL) << 56) | ((this.data[this.byteIndex + 1] & 0xffL) << 48) | ((this.data[this.byteIndex + 2] & 0xffL) << 40) | ((this.data[this.byteIndex + 3] & 0xffL) << 32) | ((this.data[this.byteIndex + 4] & 0xffL) << 24) | ((this.data[this.byteIndex + 5] & 0xffL) << 16) | ((this.data[this.byteIndex + 6] & 0xffL) << 8) | (this.data[this.byteIndex + 7] & 0xffL); this.byteIndex += 8; } public int readVarInt() throws IOException { int value = 0; int size = 0; int b; while(((b = readByte()) & 0x80) == 0x80) { value |= (b & 0x7F) << (size++ * 7); if(size > 5) { throw new IOException("Invalid VarInt. byteIndex = " + this.byteIndex + ", value = " + value + ", size = " + size); } } return value | ((b & 0x7F) << (size * 7)); } public int readByte() throws IOException { if(this.byteIndex >= this.data.length) { throw new IOException("No data to read. byteIndex = " + this.byteIndex); } return this.data[this.byteIndex++] & 0xff; } }
2,486
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
FileHelper.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/utils/FileHelper.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class FileHelper { public static String readFile(File file) throws IOException { if(!file.exists()) return null; StringBuilder text = new StringBuilder(""); BufferedReader reader = new BufferedReader(new FileReader(file)); try { String line; while ((line = reader.readLine()) != null) { text.append(line); text.append("\n"); } } finally { reader.close(); } return text.toString(); } public static void delete(File file) { if (file.isDirectory()) { for (File child : file.listFiles()) delete(child); } file.delete(); } }
871
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
Globals.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/utils/Globals.java
package com.lishid.orebfuscator.utils; public class Globals { public static final String LogPrefix = "[OFC] "; public static final int MASK_OBFUSCATE = 1; public static final int MASK_TILEENTITY = 2; public static final int MASK_PROXIMITYHIDER = 4; public static final int MASK_DARKNESSBLOCK = 8; }
306
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
MaterialHelper.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/utils/MaterialHelper.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.utils; import com.lishid.orebfuscator.NmsInstance; import org.bukkit.Material; import java.util.HashMap; import java.util.Set; public class MaterialHelper { private static HashMap<Integer, Material> _blocks; public static void init() { _blocks = new HashMap<>(); Material[] allMaterials = Material.values(); for(Material material : allMaterials) { if(material.isBlock()) { Set<Integer> ids = NmsInstance.current.getMaterialIds(material); for(int id : ids) { _blocks.put(id, material); } } } } public static Material getById(int combinedBlockId) { return _blocks.get(combinedBlockId); } public static int getMaxId() { int maxId = -1; for(int id : _blocks.keySet()) { if(id > maxId) { maxId = id; } } return maxId; } }
1,029
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ReflectionHelper.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/utils/ReflectionHelper.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.utils; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.lishid.orebfuscator.Orebfuscator; public class ReflectionHelper { public static Object getPrivateField(Class<? extends Object> c, Object object, String fieldName) { try { Field field = c.getDeclaredField(fieldName); field.setAccessible(true); return field.get(object); } catch (Exception e) { Orebfuscator.log(e); } return null; } public static Object getPrivateField(Object object, String fieldName) { return getPrivateField(object.getClass(), object, fieldName); } public static void setPrivateField(Class<? extends Object> c, Object object, String fieldName, Object value) { try { Field field = c.getDeclaredField(fieldName); field.setAccessible(true); field.set(object, value); } catch (Exception e) { Orebfuscator.log(e); } } public static void setPrivateField(Object object, String fieldName, Object value) { setPrivateField(object.getClass(), object, fieldName, value); } public static void setPrivateFinal(Object object, String fieldName, Object value) { try { Field field = object.getClass().getDeclaredField(fieldName); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(object, value); } catch (Exception e) { Orebfuscator.log(e); } } }
2,425
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
PlayerBlockTracking.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/hithack/PlayerBlockTracking.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.hithack; import org.bukkit.block.Block; import org.bukkit.entity.Player; import com.lishid.orebfuscator.Orebfuscator; public class PlayerBlockTracking { private Block block; private int hackingIndicator; private Player player; private long lastTime = System.currentTimeMillis(); public PlayerBlockTracking(Player player) { this.player = player; } public Player getPlayer() { return this.player; } public int getHackingIndicator() { return hackingIndicator; } public Block getBlock() { return block; } public boolean isBlock(Block block) { if (block == null || this.block == null) return false; return block.equals(this.block); } public void setBlock(Block block) { this.block = block; } public void incrementHackingIndicator(int value) { hackingIndicator += value; if (hackingIndicator >= (1 << 14)) { Orebfuscator.instance.runTask(new Runnable() { public void run() { String name = player.getName(); Orebfuscator.log("Player \"" + name + "\" tried to hack with packet spamming."); player.kickPlayer("End of Stream"); } }); } } public void incrementHackingIndicator() { incrementHackingIndicator(1); } public void decrementHackingIndicator(int value) { hackingIndicator -= value; if (hackingIndicator < 0) hackingIndicator = 0; } public void updateTime() { lastTime = System.currentTimeMillis(); } public long getTimeDifference() { return System.currentTimeMillis() - lastTime; } }
2,445
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
BlockHitManager.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/hithack/BlockHitManager.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.hithack; import java.util.HashMap; import org.bukkit.GameMode; import org.bukkit.block.Block; import org.bukkit.entity.Player; import com.lishid.orebfuscator.Orebfuscator; public class BlockHitManager { private static HashMap<Player, PlayerBlockTracking> playersBlockTrackingStatus = new HashMap<Player, PlayerBlockTracking>(); public static boolean hitBlock(Player player, Block block) { if (player.getGameMode() == GameMode.CREATIVE) return true; PlayerBlockTracking playerBlockTracking = getPlayerBlockTracking(player); if (playerBlockTracking.isBlock(block)) { return true; } long time = playerBlockTracking.getTimeDifference(); playerBlockTracking.incrementHackingIndicator(); playerBlockTracking.setBlock(block); playerBlockTracking.updateTime(); int decrement = (int) (time / Orebfuscator.config.getAntiHitHackDecrementFactor()); playerBlockTracking.decrementHackingIndicator(decrement); if (playerBlockTracking.getHackingIndicator() == Orebfuscator.config.getAntiHitHackMaxViolation()) playerBlockTracking.incrementHackingIndicator(Orebfuscator.config.getAntiHitHackMaxViolation()); if (playerBlockTracking.getHackingIndicator() > Orebfuscator.config.getAntiHitHackMaxViolation()) return false; return true; } public static boolean canFakeHit(Player player) { PlayerBlockTracking playerBlockTracking = getPlayerBlockTracking(player); if (playerBlockTracking.getHackingIndicator() > Orebfuscator.config.getAntiHitHackMaxViolation()) return false; return true; } public static boolean fakeHit(Player player) { PlayerBlockTracking playerBlockTracking = getPlayerBlockTracking(player); playerBlockTracking.incrementHackingIndicator(); if (playerBlockTracking.getHackingIndicator() > Orebfuscator.config.getAntiHitHackMaxViolation()) return false; return true; } public static void breakBlock(Player player, Block block) { if (player.getGameMode() == GameMode.CREATIVE) return; PlayerBlockTracking playerBlockTracking = getPlayerBlockTracking(player); if (playerBlockTracking.isBlock(block)) { playerBlockTracking.decrementHackingIndicator(2); } } private static PlayerBlockTracking getPlayerBlockTracking(Player player) { if (!playersBlockTrackingStatus.containsKey(player)) { playersBlockTrackingStatus.put(player, new PlayerBlockTracking(player)); } return playersBlockTrackingStatus.get(player); } public static void clearHistory(Player player) { playersBlockTrackingStatus.remove(player); } public static void clearAll() { playersBlockTrackingStatus.clear(); } }
3,578
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
OrebfuscatorEntityListener.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/listeners/OrebfuscatorEntityListener.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.listeners; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.*; import com.lishid.orebfuscator.obfuscation.BlockUpdate; public class OrebfuscatorEntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityExplode(EntityExplodeEvent event) { BlockUpdate.update(event.blockList()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityChangeBlock(EntityChangeBlockEvent event) { BlockUpdate.update(event.getBlock()); } }
1,353
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
OrebfuscatorPlayerListener.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/listeners/OrebfuscatorPlayerListener.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.listeners; import com.lishid.orebfuscator.NmsInstance; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.Event.Result; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import com.lishid.orebfuscator.Orebfuscator; import com.lishid.orebfuscator.hithack.BlockHitManager; import com.lishid.orebfuscator.obfuscation.BlockUpdate; import com.lishid.orebfuscator.obfuscation.ProximityHider; public class OrebfuscatorPlayerListener implements Listener { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (Orebfuscator.config.isLoginNotification()) { if (Orebfuscator.config.playerBypassOp(player)) { Orebfuscator.message(player, "Orebfuscator bypassed because you are OP."); } else if (Orebfuscator.config.playerBypassPerms(player)) { Orebfuscator.message(player, "Orebfuscator bypassed because you have permission."); } } if (Orebfuscator.config.isProximityHiderEnabled()) { ProximityHider.addPlayerToCheck(event.getPlayer(), null); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerQuit(PlayerQuitEvent event) { BlockHitManager.clearHistory(event.getPlayer()); if (Orebfuscator.config.isProximityHiderEnabled()) { ProximityHider.clearPlayer(event.getPlayer()); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerInteract(PlayerInteractEvent event) { if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.useInteractedBlock() == Result.DENY) return; //For using a hoe for farming if (event.getItem() != null && event.getItem().getType() != null && (event.getMaterial() == Material.DIRT || event.getMaterial() == Material.GRASS) && NmsInstance.current.isHoe(event.getItem().getType()) ) { BlockUpdate.update(event.getClickedBlock()); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerChangeWorld(PlayerChangedWorldEvent event) { BlockHitManager.clearHistory(event.getPlayer()); if (Orebfuscator.config.isProximityHiderEnabled()) { ProximityHider.clearBlocksForOldWorld(event.getPlayer()); ProximityHider.addPlayerToCheck(event.getPlayer(), null); } } @EventHandler(priority=EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerTeleport(PlayerTeleportEvent event) { if (Orebfuscator.config.isProximityHiderEnabled()) { if(event.getCause() != TeleportCause.END_PORTAL && event.getCause() != TeleportCause.NETHER_PORTAL ) { ProximityHider.addPlayerToCheck(event.getPlayer(), null); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerMove(PlayerMoveEvent event) { if (Orebfuscator.config.isProximityHiderEnabled()) { ProximityHider.addPlayerToCheck(event.getPlayer(), event.getFrom()); } } }
4,467
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
OrebfuscatorBlockListener.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/listeners/OrebfuscatorBlockListener.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.listeners; import com.lishid.orebfuscator.NmsInstance; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPistonRetractEvent; import com.lishid.orebfuscator.Orebfuscator; import com.lishid.orebfuscator.hithack.BlockHitManager; import com.lishid.orebfuscator.obfuscation.BlockUpdate; public class OrebfuscatorBlockListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent event) { BlockUpdate.update(event.getBlock()); BlockHitManager.breakBlock(event.getPlayer(), event.getBlock()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockDamage(BlockDamageEvent event) { if (!Orebfuscator.config.isUpdateOnDamage()) { return; } if (!BlockUpdate.needsUpdate(event.getBlock())) { return; } if (!BlockHitManager.hitBlock(event.getPlayer(), event.getBlock())) { return; } BlockUpdate.update(event.getBlock()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPhysics(BlockPhysicsEvent event) { if (event.getBlock().getType() != Material.SAND && event.getBlock().getType() != Material.GRAVEL) { return; } Material blockMaterial = event.getBlock().getRelative(0, -1, 0).getType(); if(!NmsInstance.current.canApplyPhysics(blockMaterial)) { return; } BlockUpdate.update(event.getBlock()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPistonExtend(BlockPistonExtendEvent event) { BlockUpdate.update(event.getBlocks()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPistonRetract(BlockPistonRetractEvent event) { BlockUpdate.update(event.getBlock()); } }
2,983
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
OrebfuscatorCommandExecutor.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/commands/OrebfuscatorCommandExecutor.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.commands; import java.io.IOException; import java.util.*; import com.lishid.orebfuscator.NmsInstance; import com.lishid.orebfuscator.config.WorldConfig; import com.lishid.orebfuscator.utils.Globals; import com.lishid.orebfuscator.utils.MaterialHelper; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.lishid.orebfuscator.Orebfuscator; import com.lishid.orebfuscator.cache.ObfuscatedDataCache; public class OrebfuscatorCommandExecutor { public static boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if ((sender instanceof Player) && !sender.hasPermission("Orebfuscator.admin")) { Orebfuscator.message(sender, "You do not have permissions."); return true; } if (args.length <= 0) { return false; } if (args[0].equalsIgnoreCase("engine") && args.length > 1) { int engine = Orebfuscator.config.getEngineMode(); try { engine = new Integer(args[1]); } catch (NumberFormatException e) { Orebfuscator.message(sender, args[1] + " is not a number!"); return true; } if (engine != 1 && engine != 2) { Orebfuscator.message(sender, args[1] + " is not a valid EngineMode!"); return true; } else { Orebfuscator.configManager.setEngineMode(engine); Orebfuscator.message(sender, "Engine set to: " + engine); return true; } } else if (args[0].equalsIgnoreCase("updateradius") && args.length > 1) { int radius = Orebfuscator.config.getUpdateRadius(); try { radius = new Integer(args[1]); } catch (NumberFormatException e) { Orebfuscator.message(sender, args[1] + " is not a number!"); return true; } Orebfuscator.configManager.setUpdateRadius(radius); Orebfuscator.message(sender, "UpdateRadius set to: " + Orebfuscator.config.getUpdateRadius()); return true; } else if (args[0].equalsIgnoreCase("initialradius") && args.length > 1) { int radius = Orebfuscator.config.getInitialRadius(); try { radius = new Integer(args[1]); } catch (NumberFormatException e) { Orebfuscator.message(sender, args[1] + " is not a number!"); return true; } Orebfuscator.configManager.setInitialRadius(radius); Orebfuscator.message(sender, "InitialRadius set to: " + radius); return true; } else if (args[0].equalsIgnoreCase("enable") || args[0].equalsIgnoreCase("disable")) { boolean data = args[0].equalsIgnoreCase("enable"); if (args[0].equalsIgnoreCase("enable") && args.length == 1) { Orebfuscator.configManager.setEnabled(true); Orebfuscator.message(sender, "Enabled."); return true; } else if (args[0].equalsIgnoreCase("disable") && args.length == 1) { Orebfuscator.configManager.setEnabled(false); Orebfuscator.message(sender, "Disabled."); return true; } else if (args.length > 1) { if (args[1].equalsIgnoreCase("op")) { Orebfuscator.configManager.setNoObfuscationForOps(data); Orebfuscator.message(sender, "Ops No-Obfuscation " + (data ? "enabled" : "disabled") + "."); return true; } else if (args[1].equalsIgnoreCase("perms") || args[1].equalsIgnoreCase("permissions")) { Orebfuscator.configManager.setNoObfuscationForPermission(data); Orebfuscator.message(sender, "Permissions No-Obfuscation " + (data ? "enabled" : "disabled") + "."); return true; } else if (args[1].equalsIgnoreCase("cache")) { Orebfuscator.configManager.setUseCache(data); Orebfuscator.message(sender, "Cache " + (data ? "enabled" : "disabled") + "."); return true; } else if (args[1].equalsIgnoreCase("notification")) { Orebfuscator.configManager.setLoginNotification(data); Orebfuscator.message(sender, "Login Notification " + (data ? "enabled" : "disabled") + "."); return true; } } } else if (args[0].equalsIgnoreCase("reload")) { Orebfuscator.instance.reloadOrebfuscatorConfig(); Orebfuscator.message(sender, "Reload complete."); return true; } else if (args[0].equalsIgnoreCase("status")) { String status = Orebfuscator.instance.getIsProtocolLibFound() ? (Orebfuscator.config.isEnabled() ? "Enabled" : "Disabled") : "ProtocolLib is not found! Plugin cannot be enabled."; Orebfuscator.message(sender, "Orebfuscator " + Orebfuscator.instance.getDescription().getVersion() + " is: " + status); Orebfuscator.message(sender, "Engine Mode: " + Orebfuscator.config.getEngineMode()); Orebfuscator.message(sender, "Caching: " + (Orebfuscator.config.isUseCache() ? "Enabled" : "Disabled")); Orebfuscator.message(sender, "ProximityHider: " + (Orebfuscator.config.isProximityHiderEnabled() ? "Enabled" : "Disabled")); Orebfuscator.message(sender, "DarknessHideBlocks: " + (Orebfuscator.config.getDefaultWorld().isDarknessHideBlocks() ? "Enabled": "Disabled")); Orebfuscator.message(sender, "Initial Obfuscation Radius: " + Orebfuscator.config.getInitialRadius()); Orebfuscator.message(sender, "Update Radius: " + Orebfuscator.config.getUpdateRadius()); Orebfuscator.message(sender, "World by Default: " + (Orebfuscator.config.getDefaultWorld().isEnabled() ? "Enabled" : "Disabled")); String worldNames = Orebfuscator.config.getWorldNames(); Orebfuscator.message(sender, "Worlds in List: " + (worldNames.equals("") ? "None" : worldNames)); return true; } else if (args[0].equalsIgnoreCase("clearcache")) { try { ObfuscatedDataCache.clearCache(); Orebfuscator.message(sender, "Cache cleared."); } catch (IOException e) { e.printStackTrace(); } return true; } else if (args[0].equalsIgnoreCase("obfuscateblocks")) { commandObfuscateBlocks(sender, args); return true; } else if (args[0].equalsIgnoreCase("ph")) { commandProximityHider(sender, args); return true; } else if (args[0].equalsIgnoreCase("lm")) { commandListMaterials(sender, args); return true; } else if (args[0].equalsIgnoreCase("tp")) { commandTransparentBlocks(sender, args); return true; } return false; } private static void commandObfuscateBlocks(CommandSender sender, String[] args) { if(args.length == 1) { Orebfuscator.message(sender, ChatColor.RED + "World is required parameter."); return; } String worldName = args[1]; World world = Bukkit.getWorld(worldName); if(world == null) { Orebfuscator.message(sender, ChatColor.RED + "Specified world is not found."); return; } if(args.length > 2) { Material material = Material.getMaterial(args[2]); if(material == null) { Orebfuscator.message(sender, ChatColor.RED + "Specified material is not found."); } else { int materialId = NmsInstance.current.getMaterialIds(material).iterator().next(); if((Orebfuscator.configManager.getWorld(world).getObfuscatedBits(materialId) & Globals.MASK_OBFUSCATE) != 0) Orebfuscator.message(sender, material.name() + ": " + ChatColor.GREEN + "obfuscate"); else Orebfuscator.message(sender, material.name() + ": " + ChatColor.RED + "not obfuscate"); } return; } Material[] materials = Material.values(); ArrayList<String> blockNames = new ArrayList<>(); for(Material material : materials) { if(material.isBlock()) { int blockId = NmsInstance.current.getMaterialIds(material).iterator().next(); int bits = Orebfuscator.configManager.getWorld(world).getObfuscatedBits(blockId); if(bits != 0) { blockNames.add(material.name() + " " + ChatColor.WHITE + bits); } } } Collections.sort(blockNames); StringBuilder blocks = new StringBuilder(); blocks.append("Obfuscate blocks:"); if(blockNames.size() > 0) { for (String blockName : blockNames) { blocks.append(ChatColor.GREEN + "\n - " + blockName); } } else { blocks.append(" None"); } Orebfuscator.message(sender, blocks.toString()); } private static void commandProximityHider(CommandSender sender, String[] args) { if(args.length == 1) { Orebfuscator.message(sender, ChatColor.RED + "World is required parameter."); return; } WorldConfig worldConfig = null; String worldName = args[1]; if(worldName.startsWith(":")) { if(worldName.equalsIgnoreCase(":default")) { worldConfig = Orebfuscator.config.getDefaultWorld(); } else if(worldName.equalsIgnoreCase(":normal")) { worldConfig = Orebfuscator.config.getNormalWorld(); } else if(worldName.equalsIgnoreCase(":nether")) { worldConfig = Orebfuscator.config.getNetherWorld(); } else if(worldName.equalsIgnoreCase(":end")) { worldConfig = Orebfuscator.config.getEndWorld(); } } else { World world = Bukkit.getWorld(worldName); worldConfig = Orebfuscator.configManager.getWorld(world); } if (worldConfig == null) { Orebfuscator.message(sender, ChatColor.RED + "Specified world is not found."); return; } Orebfuscator.message(sender, "ProximityHider: " + (worldConfig.getProximityHiderConfig().isEnabled() ? "Enabled" : "Disabled")); StringBuilder blocks = new StringBuilder(); blocks.append("Obfuscate blocks:"); Set<Integer> blockIds = worldConfig.getProximityHiderConfig().getProximityHiderBlocks(); if(blockIds.size() > 0) { ArrayList<String> blockNames = new ArrayList<>(); for (int id : blockIds) { blockNames.add(MaterialHelper.getById(id).name()); } Collections.sort(blockNames); for (String blockName : blockNames) { blocks.append("\n - " + blockName); } } else { blocks.append(" None"); } Orebfuscator.message(sender, blocks.toString()); } private static void commandListMaterials(CommandSender sender, String[] args) { Material[] materials = Material.values(); List<String> blockNames = new ArrayList<>(); for (Material material : materials) { if(material.isBlock()) { List<Integer> ids = new ArrayList<>(NmsInstance.current.getMaterialIds(material)); Collections.sort(ids); for(int id : ids) { blockNames.add(material.name() + " = " + id); } } } Collections.sort(blockNames); StringBuilder blocks = new StringBuilder(); for (String blockName : blockNames) { blocks.append("\n - " + blockName); } Orebfuscator.message(sender, blocks.toString()); } private static void commandTransparentBlocks(CommandSender sender, String[] args) { Material[] materials = Material.values(); List<String> transparentBlockNames = new ArrayList<>(); List<String> nonTransparentBlockNames = new ArrayList<>(); for (Material material : materials) { if(material.isBlock()) { int blockId = NmsInstance.current.getMaterialIds(material).iterator().next(); boolean isTransparent = Orebfuscator.config.isBlockTransparent(blockId); if(isTransparent) { transparentBlockNames.add(material.name()); } else { nonTransparentBlockNames.add(material.name()); } } } Collections.sort(transparentBlockNames); Collections.sort(nonTransparentBlockNames); StringBuilder blocks = new StringBuilder(); blocks.append("Transparent blocks:"); for (String blockName : transparentBlockNames) { blocks.append("\n - " + blockName); } blocks.append("\nNon-Transparent blocks:"); for (String blockName : nonTransparentBlockNames) { blocks.append("\n - " + blockName); } Orebfuscator.message(sender, blocks.toString()); } }
14,514
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
CacheCleaner.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/cache/CacheCleaner.java
package com.lishid.orebfuscator.cache; import java.io.File; import org.bukkit.Bukkit; import org.bukkit.World; import com.lishid.orebfuscator.Orebfuscator; public class CacheCleaner implements Runnable { public void run() { if(!Orebfuscator.config.isEnabled() || Orebfuscator.config.getDeleteCacheFilesAfterDays() <= 0) return; int count = 0; for(World world : Bukkit.getWorlds()) { File cacheFolder = new File(ObfuscatedDataCache.getCacheFolder(), world.getName()); count += ObfuscatedDataCache.deleteFiles(cacheFolder, Orebfuscator.config.getDeleteCacheFilesAfterDays()); } Orebfuscator.log("Cache cleaner completed, deleted files: " + count); } }
741
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ObfuscatedCachedChunk.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/cache/ObfuscatedCachedChunk.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.cache; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import com.lishid.orebfuscator.NmsInstance; import com.lishid.orebfuscator.nms.INBT; public class ObfuscatedCachedChunk { File path; int x; int z; public byte[] data; public int[] proximityList; public int[] removedEntityList; public long hash = 0L; private boolean loaded = false; private static final ThreadLocal<INBT> nbtAccessor = new ThreadLocal<INBT>() { protected INBT initialValue() { return NmsInstance.current.createNBT(); } }; public ObfuscatedCachedChunk(File file, int x, int z) { this.x = x; this.z = z; this.path = new File(file, "data"); path.mkdirs(); } public void invalidate() { write(0L, new byte[0], new int[0], new int[0]); } public void free() { data = null; proximityList = null; removedEntityList = null; } public long getHash() { read(); if (!loaded) return 0L; return hash; } public void read() { if (loaded) return; try { DataInputStream stream = ObfuscatedDataCache.getInputStream(path, x, z); if (stream != null) { INBT nbt = nbtAccessor.get(); nbt.Read(stream); // Check if statuses makes sense if (nbt.getInt("X") != x || nbt.getInt("Z") != z) return; // Get Hash hash = nbt.getLong("Hash"); // Get Data data = nbt.getByteArray("Data"); proximityList = nbt.getIntArray("ProximityList"); removedEntityList = nbt.getIntArray("RemovedEntityList"); loaded = true; } } catch (Exception e) { // Orebfuscator.log("Error reading Cache: " + e.getMessage()); // e.printStackTrace(); loaded = false; } } public void write(long hash, byte[] data, int[] proximityList, int[] removedEntityList) { try { INBT nbt = nbtAccessor.get(); nbt.reset(); // Set status indicator nbt.setInt("X", x); nbt.setInt("Z", z); // Set hash nbt.setLong("Hash", hash); // Set data nbt.setByteArray("Data", data); nbt.setIntArray("ProximityList", proximityList); nbt.setIntArray("RemovedEntityList", removedEntityList); DataOutputStream stream = ObfuscatedDataCache.getOutputStream(path, x, z); nbt.Write(stream); try { stream.close(); } catch (Exception e) { } } catch (Exception e) { // Orebfuscator.log("Error reading Cache: " + e.getMessage()); // e.printStackTrace(); } } }
3,661
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ObfuscatedDataCache.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/cache/ObfuscatedDataCache.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.cache; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.Objects; import com.lishid.orebfuscator.NmsInstance; import org.bukkit.Bukkit; import com.lishid.orebfuscator.Orebfuscator; import com.lishid.orebfuscator.nms.IChunkCache; import com.lishid.orebfuscator.utils.FileHelper; public class ObfuscatedDataCache { private static final String cacheFileName = "cache_config.yml"; private static File cacheFolder; private static IChunkCache internalCache; private static IChunkCache getInternalCache() { if (internalCache == null) { internalCache = NmsInstance.current.createChunkCache(); } return internalCache; } public static void resetCacheFolder() { cacheFolder = null; } public static File getCacheFolder() { if(cacheFolder == null) { cacheFolder = new File(Bukkit.getServer().getWorldContainer(), Orebfuscator.config.getCacheLocation()); } // Try to make the folder if (!cacheFolder.exists()) { cacheFolder.mkdirs(); } // Can't make folder? Use default if (!cacheFolder.exists()) { cacheFolder = new File("orebfuscator_cache"); } return cacheFolder; } public static void closeCacheFiles() { getInternalCache().closeCacheFiles(); } public static void checkCacheAndConfigSynchronized() throws IOException { String configContent = Orebfuscator.instance.getConfig().saveToString(); File cacheFolder = getCacheFolder(); File cacheConfigFile = new File(cacheFolder, cacheFileName); String cacheConfigContent = FileHelper.readFile(cacheConfigFile); if(Objects.equals(configContent, cacheConfigContent)) return; clearCache(); } public static void clearCache() throws IOException { closeCacheFiles(); File cacheFolder = getCacheFolder(); File cacheConfigFile = new File(cacheFolder, cacheFileName); if(cacheFolder.exists()) { FileHelper.delete(cacheFolder); } Orebfuscator.log("Cache cleared."); cacheFolder.mkdirs(); Orebfuscator.instance.getConfig().save(cacheConfigFile); } public static DataInputStream getInputStream(File folder, int x, int z) { return getInternalCache().getInputStream(folder, x, z); } public static DataOutputStream getOutputStream(File folder, int x, int z) { return getInternalCache().getOutputStream(folder, x, z); } public static int deleteFiles(File folder, int deleteAfterDays) { int count = 0; try { File regionFolder = new File(folder, "data/region"); if(!regionFolder.exists()) return count; long deleteAfterDaysMs = (long)deleteAfterDays * 24L * 60L * 60L * 1000L; for(File file : regionFolder.listFiles()) { long diff = new Date().getTime() - file.lastModified(); if (diff > deleteAfterDaysMs) { file.delete(); count++; } } } catch(Exception ex) { ex.printStackTrace(); } return count; } }
3,909
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
Calculations.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/obfuscation/Calculations.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.obfuscation; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import com.lishid.orebfuscator.NmsInstance; import com.lishid.orebfuscator.utils.Globals; import org.bukkit.World; import org.bukkit.entity.Player; import com.comphenix.protocol.wrappers.nbt.NbtBase; import com.comphenix.protocol.wrappers.nbt.NbtCompound; import com.comphenix.protocol.wrappers.nbt.NbtType; import com.lishid.orebfuscator.Orebfuscator; import com.lishid.orebfuscator.cache.ObfuscatedCachedChunk; import com.lishid.orebfuscator.cache.ObfuscatedDataCache; import com.lishid.orebfuscator.chunkmap.ChunkData; import com.lishid.orebfuscator.chunkmap.ChunkMapManager; import com.lishid.orebfuscator.config.ProximityHiderConfig; import com.lishid.orebfuscator.config.WorldConfig; import com.lishid.orebfuscator.types.BlockCoord; public class Calculations { public static class Result { public byte[] output; public ArrayList<BlockCoord> removedEntities; } private static Random random = new Random(); public static Result obfuscateOrUseCache(ChunkData chunkData, Player player, WorldConfig worldConfig) throws Exception { if(chunkData.primaryBitMask == 0) return null; byte[] output; ArrayList<BlockCoord> removedEntities; ObfuscatedCachedChunk cache = tryUseCache(chunkData, player); if(cache != null && cache.data != null) { //Orebfuscator.log("Read from cache");/*debug*/ output = cache.data; removedEntities = getCoordFromArray(cache.removedEntityList); } else { // Blocks kept track for ProximityHider ArrayList<BlockCoord> proximityBlocks = new ArrayList<>(); removedEntities = new ArrayList<>(); output = obfuscate(worldConfig, chunkData, player, proximityBlocks, removedEntities); if (cache != null) { // If cache is still allowed if(chunkData.useCache) { // Save cache int[] proximityList = getArrayFromCoord(proximityBlocks); int[] removedEntityList = getArrayFromCoord(removedEntities); cache.write(cache.hash, output, proximityList, removedEntityList); //Orebfuscator.log("Write to cache");/*debug*/ } cache.free(); } } //Orebfuscator.log("Send chunk x = " + chunkData.chunkX + ", z = " + chunkData.chunkZ + " to player " + player.getName());/*debug*/ Result result = new Result(); result.output = output; result.removedEntities = removedEntities; return result; } private static int[] getArrayFromCoord(ArrayList<BlockCoord> coords) { int[] list = new int[coords.size() * 3]; int index = 0; for (int i = 0; i < coords.size(); i++) { BlockCoord b = coords.get(i); if (b != null) { list[index++] = b.x; list[index++] = b.y; list[index++] = b.z; } } return list; } private static ArrayList<BlockCoord> getCoordFromArray(int[] array) { ArrayList<BlockCoord> list = new ArrayList<>(); // Decrypt chest list if (array != null) { int index = 0; while (index < array.length) { int x = array[index++]; int y = array[index++]; int z = array[index++]; BlockCoord b = new BlockCoord(x, y, z); if(b != null) { list.add(b); } } } return list; } private static byte[] obfuscate( WorldConfig worldConfig, ChunkData chunkData, Player player, ArrayList<BlockCoord> proximityBlocks, ArrayList<BlockCoord> removedEntities ) throws Exception { ProximityHiderConfig proximityHider = worldConfig.getProximityHiderConfig(); int initialRadius = Orebfuscator.config.getInitialRadius(); // Track of pseudo-randomly assigned randomBlock int randomIncrement = 0; int randomIncrement2 = 0; int randomCave = 0; int engineMode = Orebfuscator.config.getEngineMode(); int maxChance = worldConfig.getAirGeneratorMaxChance(); int randomBlocksLength = worldConfig.getRandomBlocks().length; boolean randomAlternate = false; int startX = chunkData.chunkX << 4; int startZ = chunkData.chunkZ << 4; byte[] output; try (ChunkMapManager manager = ChunkMapManager.create(chunkData)) { for (int i = 0; i < manager.getSectionCount(); i++) { worldConfig.shuffleRandomBlocks(); for (int offsetY = 0; offsetY < 16; offsetY++) { for (int offsetZ = 0; offsetZ < 16; offsetZ++) { int incrementMax = (maxChance + random(maxChance)) / 2; for (int offsetX = 0; offsetX < 16; offsetX++) { int blockData = manager.readNextBlock(); int x = startX | offsetX; int y = manager.getY(); int z = startZ | offsetZ; // Initialize data int obfuscateBits = worldConfig.getObfuscatedBits(blockData); boolean obfuscateFlag = (obfuscateBits & Globals.MASK_OBFUSCATE) != 0; boolean proximityHiderFlag = (obfuscateBits & Globals.MASK_PROXIMITYHIDER) != 0; boolean darknessBlockFlag = (obfuscateBits & Globals.MASK_DARKNESSBLOCK) != 0; boolean tileEntityFlag = (obfuscateBits & Globals.MASK_TILEENTITY) != 0; boolean obfuscate = false; boolean specialObfuscate = false; // Check if the block should be obfuscated for the default engine modes if (obfuscateFlag) { if (initialRadius == 0) { // Do not interfere with PH if (proximityHiderFlag && proximityHider.isEnabled() && proximityHider.isProximityObfuscated(y, blockData)) { if (!areAjacentBlocksTransparent(manager, player.getWorld(), false, x, y, z, 1)) { obfuscate = true; } } else { // Obfuscate all blocks obfuscate = true; } } else { // Check if any nearby blocks are transparent if (!areAjacentBlocksTransparent(manager, player.getWorld(), false, x, y, z, initialRadius)) { obfuscate = true; } } } // Check if the block should be obfuscated because of proximity check if (!obfuscate && proximityHiderFlag && proximityHider.isEnabled() && proximityHider.isProximityObfuscated(y, blockData)) { BlockCoord block = new BlockCoord(x, y, z); if (block != null) { proximityBlocks.add(block); } obfuscate = true; if (proximityHider.isUseSpecialBlock()) { specialObfuscate = true; } } // Check if the block is obfuscated if (obfuscate && (!worldConfig.isBypassObfuscationForSignsWithText() || canObfuscate(chunkData, x, y, z, blockData))) { if (specialObfuscate) { // Proximity hider blockData = proximityHider.getSpecialBlockID(); } else { if (engineMode == 1) { // Engine mode 1, replace with stone blockData = worldConfig.getMode1BlockId(); } else if (engineMode == 2) { // Ending mode 2, replace with random block if (randomBlocksLength > 1) { randomIncrement = CalculationsUtil.increment(randomIncrement, randomBlocksLength); } blockData = worldConfig.getRandomBlock(randomIncrement, randomAlternate); randomAlternate = !randomAlternate; } // Anti texturepack and freecam if (worldConfig.isAntiTexturePackAndFreecam()) { // Add random air blocks randomIncrement2 = random(incrementMax); if (randomIncrement2 == 0) { randomCave = 1 + random(3); } if (randomCave > 0) { blockData = NmsInstance.current.getCaveAirBlockId(); randomCave--; } } } } // Check if the block should be obfuscated because of the darkness if (!obfuscate && darknessBlockFlag && worldConfig.isDarknessHideBlocks()) { if (!areAjacentBlocksBright(player.getWorld(), x, y, z, 1)) { // Hide block, setting it to air blockData = NmsInstance.current.getCaveAirBlockId(); obfuscate = true; } } if (obfuscate && tileEntityFlag) { removedEntities.add(new BlockCoord(x, y, z)); } if (offsetY == 0 && offsetZ == 0 && offsetX == 0) { manager.finalizeOutput(); manager.initOutputPalette(); addBlocksToPalette(manager, worldConfig); manager.initOutputSection(); } manager.writeOutputBlock(blockData); } } } } manager.finalizeOutput(); output = manager.createOutput(); } ProximityHider.addProximityBlocks(player, chunkData.chunkX, chunkData.chunkZ, proximityBlocks); //Orebfuscator.log("Create new chunk data for x = " + chunkData.chunkX + ", z = " + chunkData.chunkZ);/*debug*/ return output; } private static boolean canObfuscate(ChunkData chunkData, int x, int y, int z, int blockData) { if(!NmsInstance.current.isSign(blockData)) { return true; } NbtCompound tag = getBlockEntity(chunkData, x, y, z); return tag == null || isSignTextEmpty(tag, "Text1") && isSignTextEmpty(tag, "Text2") && isSignTextEmpty(tag, "Text3") && isSignTextEmpty(tag, "Text4"); } private static boolean isSignTextEmpty(NbtCompound compound, String key) { NbtBase<?> tag = compound.getValue(key); if(tag == null || tag.getType() != NbtType.TAG_STRING) { return true; } String json = (String)tag.getValue(); if(json == null || json.isEmpty()) { return true; } String text = NmsInstance.current.getTextFromChatComponent(json); return text == null || text.isEmpty(); } private static NbtCompound getBlockEntity(ChunkData chunkData, int x, int y, int z) { for(NbtCompound tag : chunkData.blockEntities) { if(tag != null && x == tag.getInteger("x") && y == tag.getInteger("y") && z == tag.getInteger("z") ) { return tag; } } return null; } private static void addBlocksToPalette(ChunkMapManager manager, WorldConfig worldConfig) { if(!manager.inputHasNonAirBlock()) { return; } for(int id : worldConfig.getPaletteBlocks()) { manager.addToOutputPalette(id); } } private static ObfuscatedCachedChunk tryUseCache(ChunkData chunkData, Player player) { if (!Orebfuscator.config.isUseCache()) return null; chunkData.useCache = true; // Hash the chunk long hash = CalculationsUtil.Hash(chunkData.data, chunkData.data.length); // Get cache folder File cacheFolder = new File(ObfuscatedDataCache.getCacheFolder(), player.getWorld().getName()); // Create cache objects ObfuscatedCachedChunk cache = new ObfuscatedCachedChunk(cacheFolder, chunkData.chunkX, chunkData.chunkZ); // Check if hash is consistent cache.read(); long storedHash = cache.getHash(); if (storedHash == hash && cache.data != null) { int[] proximityList = cache.proximityList; ArrayList<BlockCoord> proximityBlocks = getCoordFromArray(proximityList); // ProximityHider add blocks ProximityHider.addProximityBlocks(player, chunkData.chunkX, chunkData.chunkZ, proximityBlocks); // Hash match, use the cached data instead and skip calculations return cache; } cache.hash = hash; cache.data = null; return cache; } public static boolean areAjacentBlocksTransparent( ChunkMapManager manager, World world, boolean checkCurrentBlock, int x, int y, int z, int countdown ) throws IOException { if (y >= world.getMaxHeight() || y < 0) return true; if(checkCurrentBlock) { ChunkData chunkData = manager.getChunkData(); int blockData = manager.get(x, y, z); if (blockData < 0) { blockData = NmsInstance.current.loadChunkAndGetBlockId(world, x, y, z); if (blockData < 0) { chunkData.useCache = false; } } if (blockData >= 0 && Orebfuscator.config.isBlockTransparent(blockData)) { return true; } } if (countdown == 0) return false; if (areAjacentBlocksTransparent(manager, world, true, x, y + 1, z, countdown - 1)) return true; if (areAjacentBlocksTransparent(manager, world, true, x, y - 1, z, countdown - 1)) return true; if (areAjacentBlocksTransparent(manager, world, true, x + 1, y, z, countdown - 1)) return true; if (areAjacentBlocksTransparent(manager, world, true, x - 1, y, z, countdown - 1)) return true; if (areAjacentBlocksTransparent(manager, world, true, x, y, z + 1, countdown - 1)) return true; if (areAjacentBlocksTransparent(manager, world, true, x, y, z - 1, countdown - 1)) return true; return false; } public static boolean areAjacentBlocksBright(World world, int x, int y, int z, int countdown) { if(NmsInstance.current.getBlockLightLevel(world, x, y, z) > 0) { return true; } if (countdown == 0) return false; if (areAjacentBlocksBright(world, x, y + 1, z, countdown - 1)) return true; if (areAjacentBlocksBright(world, x, y - 1, z, countdown - 1)) return true; if (areAjacentBlocksBright(world, x + 1, y, z, countdown - 1)) return true; if (areAjacentBlocksBright(world, x - 1, y, z, countdown - 1)) return true; if (areAjacentBlocksBright(world, x, y, z + 1, countdown - 1)) return true; if (areAjacentBlocksBright(world, x, y, z - 1, countdown - 1)) return true; return false; } private static int random(int max) { return random.nextInt(max); } }
14,767
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
BlockUpdate.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/obfuscation/BlockUpdate.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.obfuscation; import java.io.File; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import com.lishid.orebfuscator.NmsInstance; import com.lishid.orebfuscator.utils.Globals; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import com.lishid.orebfuscator.Orebfuscator; import com.lishid.orebfuscator.cache.ObfuscatedCachedChunk; import com.lishid.orebfuscator.cache.ObfuscatedDataCache; import com.lishid.orebfuscator.config.WorldConfig; import com.lishid.orebfuscator.nms.IBlockInfo; import com.lishid.orebfuscator.types.ChunkCoord; public class BlockUpdate { public static boolean needsUpdate(Block block) { int materialId = NmsInstance.current.getMaterialIds(block.getType()).iterator().next(); return !Orebfuscator.config.isBlockTransparent(materialId); } public static void update(Block block) { if (!needsUpdate(block)) { return; } update(Arrays.asList(new Block[]{block})); } public static void update(List<Block> blocks) { if (blocks.isEmpty()) { return; } World world = blocks.get(0).getWorld(); WorldConfig worldConfig = Orebfuscator.configManager.getWorld(world); HashSet<IBlockInfo> updateBlocks = new HashSet<IBlockInfo>(); HashSet<ChunkCoord> invalidChunks = new HashSet<ChunkCoord>(); int updateRadius = Orebfuscator.config.getUpdateRadius(); for (Block block : blocks) { if (needsUpdate(block)) { IBlockInfo blockInfo = NmsInstance.current.getBlockInfo(world, block.getX(), block.getY(), block.getZ()); getAdjacentBlocks(updateBlocks, world, worldConfig, blockInfo, updateRadius); if((blockInfo.getX() & 0xf) == 0) { invalidChunks.add(new ChunkCoord((blockInfo.getX() >> 4) - 1, blockInfo.getZ() >> 4)); } else if(((blockInfo.getX() + 1) & 0xf) == 0) { invalidChunks.add(new ChunkCoord((blockInfo.getX() >> 4) + 1, blockInfo.getZ() >> 4)); } else if(((blockInfo.getZ()) & 0xf) == 0) { invalidChunks.add(new ChunkCoord(blockInfo.getX() >> 4, (blockInfo.getZ() >> 4) - 1)); } else if(((blockInfo.getZ() + 1) & 0xf) == 0) { invalidChunks.add(new ChunkCoord(blockInfo.getX() >> 4, (blockInfo.getZ() >> 4) + 1)); } } } sendUpdates(world, updateBlocks); invalidateCachedChunks(world, invalidChunks); } //This method is used in CastleGates plugin public static void updateByLocations(List<Location> locations, int updateRadius) { if (locations.isEmpty()) { return; } World world = locations.get(0).getWorld(); WorldConfig worldConfig = Orebfuscator.configManager.getWorld(world); HashSet<IBlockInfo> updateBlocks = new HashSet<IBlockInfo>(); HashSet<ChunkCoord> invalidChunks = new HashSet<ChunkCoord>(); for (Location location : locations) { IBlockInfo blockInfo = NmsInstance.current.getBlockInfo(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); getAdjacentBlocks(updateBlocks, world, worldConfig, blockInfo, updateRadius); if((blockInfo.getX() & 0xf) == 0) { invalidChunks.add(new ChunkCoord((blockInfo.getX() >> 4) - 1, blockInfo.getZ() >> 4)); } else if(((blockInfo.getX() + 1) & 0xf) == 0) { invalidChunks.add(new ChunkCoord((blockInfo.getX() >> 4) + 1, blockInfo.getZ() >> 4)); } else if(((blockInfo.getZ()) & 0xf) == 0) { invalidChunks.add(new ChunkCoord(blockInfo.getX() >> 4, (blockInfo.getZ() >> 4) - 1)); } else if(((blockInfo.getZ() + 1) & 0xf) == 0) { invalidChunks.add(new ChunkCoord(blockInfo.getX() >> 4, (blockInfo.getZ() >> 4) + 1)); } } sendUpdates(world, updateBlocks); invalidateCachedChunks(world, invalidChunks); } private static void sendUpdates(World world, Set<IBlockInfo> blocks) { //Orebfuscator.log("Notify block change for " + blocks.size() + " blocks");/*debug*/ for (IBlockInfo blockInfo : blocks) { NmsInstance.current.notifyBlockChange(world, blockInfo); } } private static void invalidateCachedChunks(World world, Set<ChunkCoord> invalidChunks) { if(invalidChunks.isEmpty() || !Orebfuscator.config.isUseCache()) return; File cacheFolder = new File(ObfuscatedDataCache.getCacheFolder(), world.getName()); for(ChunkCoord chunk : invalidChunks) { ObfuscatedCachedChunk cache = new ObfuscatedCachedChunk(cacheFolder, chunk.x, chunk.z); cache.invalidate(); //Orebfuscator.log("Chunk x = " + chunk.x + ", z = " + chunk.z + " is invalidated");/*debug*/ } } private static void getAdjacentBlocks( HashSet<IBlockInfo> allBlocks, World world, WorldConfig worldConfig, IBlockInfo blockInfo, int countdown ) { if (blockInfo == null) return; int blockId = blockInfo.getCombinedId(); if ((worldConfig.getObfuscatedBits(blockId) & Globals.MASK_OBFUSCATE) != 0) { allBlocks.add(blockInfo); } if (countdown > 0) { countdown--; getAdjacentBlocks(allBlocks, world, worldConfig, NmsInstance.current.getBlockInfo(world, blockInfo.getX() + 1, blockInfo.getY(), blockInfo.getZ()), countdown); getAdjacentBlocks(allBlocks, world, worldConfig, NmsInstance.current.getBlockInfo(world, blockInfo.getX() - 1, blockInfo.getY(), blockInfo.getZ()), countdown); getAdjacentBlocks(allBlocks, world, worldConfig, NmsInstance.current.getBlockInfo(world, blockInfo.getX(), blockInfo.getY() + 1, blockInfo.getZ()), countdown); getAdjacentBlocks(allBlocks, world, worldConfig, NmsInstance.current.getBlockInfo(world, blockInfo.getX(), blockInfo.getY() - 1, blockInfo.getZ()), countdown); getAdjacentBlocks(allBlocks, world, worldConfig, NmsInstance.current.getBlockInfo(world, blockInfo.getX(), blockInfo.getY(), blockInfo.getZ() + 1), countdown); getAdjacentBlocks(allBlocks, world, worldConfig, NmsInstance.current.getBlockInfo(world, blockInfo.getX(), blockInfo.getY(), blockInfo.getZ() - 1), countdown); } } }
7,194
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ProximityHiderPlayer.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/obfuscation/ProximityHiderPlayer.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.obfuscation; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.bukkit.World; import com.lishid.orebfuscator.types.BlockCoord; public class ProximityHiderPlayer { private World world; private Map<Long, ArrayList<BlockCoord>> chunks; public ProximityHiderPlayer(World world) { this.world = world; this.chunks = new HashMap<Long, ArrayList<BlockCoord>>(); } public World getWorld() { return this.world; } public void setWorld(World world) { this.world = world; } public void clearChunks() { this.chunks.clear(); } public void putBlocks(int chunkX, int chunkZ, ArrayList<BlockCoord> blocks) { long key = getKey(chunkX, chunkZ); this.chunks.put(key, blocks); } public ArrayList<BlockCoord> getBlocks(int chunkX, int chunkZ) { long key = getKey(chunkX, chunkZ); return this.chunks.get(key); } public void copyChunks(ProximityHiderPlayer playerInfo) { this.chunks.putAll(playerInfo.chunks); } public void removeChunk(int chunkX, int chunkZ) { long key = getKey(chunkX, chunkZ); this.chunks.remove(key); } private static long getKey(int chunkX, int chunkZ) { return ((chunkZ & 0xffffffffL) << 32) | (chunkX & 0xffffffffL); } }
1,294
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ProximityHider.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/obfuscation/ProximityHider.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.obfuscation; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import com.lishid.orebfuscator.NmsInstance; import com.lishid.orebfuscator.nms.IBlockInfo; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import com.lishid.orebfuscator.Orebfuscator; import com.lishid.orebfuscator.config.ProximityHiderConfig; import com.lishid.orebfuscator.config.WorldConfig; import com.lishid.orebfuscator.types.BlockCoord; public class ProximityHider extends Thread implements Runnable { private static final Map<Player, ProximityHiderPlayer> proximityHiderTracker = new HashMap<Player, ProximityHiderPlayer>(); private static final Map<Player, Location> playersToCheck = new HashMap<Player, Location>(); private static final HashSet<Player> playersToReload = new HashSet<Player>(); private static ProximityHider thread = new ProximityHider(); private Map<Player, ProximityHiderPlayer> proximityHiderTrackerLocal = new HashMap<Player, ProximityHiderPlayer>(); private long lastExecute = System.currentTimeMillis(); private AtomicBoolean kill = new AtomicBoolean(false); private static boolean running = false; public static void Load() { running = true; if (thread == null || thread.isInterrupted() || !thread.isAlive()) { thread = new ProximityHider(); thread.setName("Orebfuscator ProximityHider Thread"); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } } public static void terminate() { if (thread != null) { thread.kill.set(true); } } public void run() { while (!this.isInterrupted() && !kill.get()) { try { // Wait until necessary long timeWait = lastExecute + Orebfuscator.config.getProximityHiderRate() - System.currentTimeMillis(); lastExecute = System.currentTimeMillis(); if (timeWait > 0) { Thread.sleep(timeWait); } if (!Orebfuscator.config.isProximityHiderEnabled()) { running = false; return; } HashMap<Player, Location> checkPlayers = new HashMap<Player, Location>(); synchronized (playersToCheck) { checkPlayers.putAll(playersToCheck); playersToCheck.clear(); } for (Player p : checkPlayers.keySet()) { if (p == null) { continue; } synchronized (proximityHiderTracker) { if (!proximityHiderTracker.containsKey(p)) { continue; } } Location oldLocation = checkPlayers.get(p); if(oldLocation != null) { Location curLocation = p.getLocation(); // Player didn't actually move if (curLocation.getBlockX() == oldLocation.getBlockX() && curLocation.getBlockY() == oldLocation.getBlockY() && curLocation.getBlockZ() == oldLocation.getBlockZ()) { continue; } } ProximityHiderPlayer localPlayerInfo = proximityHiderTrackerLocal.get(p); if(localPlayerInfo == null) { proximityHiderTrackerLocal.put(p, localPlayerInfo = new ProximityHiderPlayer(p.getWorld())); } synchronized (proximityHiderTracker) { ProximityHiderPlayer playerInfo = proximityHiderTracker.get(p); if (playerInfo != null) { if(!localPlayerInfo.getWorld().equals(playerInfo.getWorld())) { localPlayerInfo.setWorld(playerInfo.getWorld()); localPlayerInfo.clearChunks(); } localPlayerInfo.copyChunks(playerInfo); playerInfo.clearChunks(); } } if(localPlayerInfo.getWorld() == null || p.getWorld() == null || !p.getWorld().equals(localPlayerInfo.getWorld())) { localPlayerInfo.clearChunks(); continue; } WorldConfig worldConfig = Orebfuscator.configManager.getWorld(p.getWorld()); ProximityHiderConfig proximityHider = worldConfig.getProximityHiderConfig(); int checkRadius = proximityHider.getDistance() >> 4; if((proximityHider.getDistance() & 0xf) != 0) { checkRadius++; } int distanceSquared = proximityHider.getDistanceSquared(); ArrayList<BlockCoord> removedBlocks = new ArrayList<BlockCoord>(); Location playerLocation = p.getLocation(); // 4.3.1 -- GAZE CHECK Location playerEyes = p.getEyeLocation(); // 4.3.1 -- GAZE CHECK END int minChunkX = (playerLocation.getBlockX() >> 4) - checkRadius; int maxChunkX = minChunkX + (checkRadius << 1); int minChunkZ = (playerLocation.getBlockZ() >> 4) - checkRadius; int maxChunkZ = minChunkZ + (checkRadius << 1); for(int chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) { for(int chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) { ArrayList<BlockCoord> blocks = localPlayerInfo.getBlocks(chunkX, chunkZ); if(blocks == null) continue; removedBlocks.clear(); for (BlockCoord b : blocks) { if (b == null) { removedBlocks.add(b); continue; } Location blockLocation = new Location(localPlayerInfo.getWorld(), b.x, b.y, b.z); if (proximityHider.isObfuscateAboveY() || playerLocation.distanceSquared(blockLocation) < distanceSquared) { // 4.3.1 -- GAZE CHECK if (!proximityHider.isUseFastGazeCheck() || doFastCheck(blockLocation, playerEyes, localPlayerInfo.getWorld())) { // 4.3.1 -- GAZE CHECK END removedBlocks.add(b); if (NmsInstance.current.sendBlockChange(p, blockLocation)) { final BlockCoord block = b; final Player player = p; Orebfuscator.instance.runTask(new Runnable() { public void run() { NmsInstance.current.updateBlockTileEntity(block, player); } }); } } } } if(blocks.size() == removedBlocks.size()) { localPlayerInfo.removeChunk(chunkX, chunkZ); } else { blocks.removeAll(removedBlocks); } } } } } catch (Exception e) { Orebfuscator.log(e); } } running = false; } /** * Basic idea here is to take some rays from the considered block to the player's eyes, and decide if * any of those rays can reach the eyes unimpeded. * * @param block the starting block * @param eyes the destination eyes * @param player the player world we are testing for * @return true if unimpeded path, false otherwise */ private boolean doFastCheck(Location block, Location eyes, World player) { double ex = eyes.getX(); double ey = eyes.getY(); double ez = eyes.getZ(); double x = block.getBlockX(); double y = block.getBlockY(); double z = block.getBlockZ(); return // midfaces fastAABBRayCheck(x, y, z, x , y+0.5, z+0.5, ex, ey, ez, player) || fastAABBRayCheck(x, y, z, x+0.5, y , z+0.5, ex, ey, ez, player) || fastAABBRayCheck(x, y, z, x+0.5, y+0.5, z , ex, ey, ez, player) || fastAABBRayCheck(x, y, z, x+0.5, y+1.0, z+0.5, ex, ey, ez, player) || fastAABBRayCheck(x, y, z, x+0.5, y+0.5, z+1.0, ex, ey, ez, player) || fastAABBRayCheck(x, y, z, x+1.0, y+0.5, z+0.5, ex, ey, ez, player) || // corners fastAABBRayCheck(x, y, z, x , y , z , ex, ey, ez, player) || fastAABBRayCheck(x, y, z, x+1, y , z , ex, ey, ez, player) || fastAABBRayCheck(x, y, z, x , y+1, z , ex, ey, ez, player) || fastAABBRayCheck(x, y, z, x+1, y+1, z , ex, ey, ez, player) || fastAABBRayCheck(x, y, z, x , y , z+1, ex, ey, ez, player) || fastAABBRayCheck(x, y, z, x+1, y , z+1, ex, ey, ez, player) || fastAABBRayCheck(x, y, z, x , y+1, z+1, ex, ey, ez, player) || fastAABBRayCheck(x, y, z, x+1, y+1, z+1, ex, ey, ez, player); } private boolean fastAABBRayCheck(double bx, double by, double bz, double x, double y, double z, double ex, double ey, double ez, World world) { double fx = ex - x; double fy = ey - y; double fz = ez - z; double absFx = Math.abs(fx); double absFy = Math.abs(fy); double absFz = Math.abs(fz); double s = Math.max(absFx, Math.max(absFy, absFz)); if (s < 1) return true; // on top / inside double lx, ly, lz; fx = fx / s; // units of change along vector fy = fy / s; fz = fz / s; while (s > 0) { ex = ex - fx; // move along vector, we start _at_ the eye and move towards b ey = ey - fy; ez = ez - fz; lx = Math.floor(ex); ly = Math.floor(ey); lz = Math.floor(ez); if (lx == bx && ly == by && lz == bz) return true; // we've reached our starting block, don't test it. IBlockInfo between = NmsInstance.current.getBlockInfo(world, (int) lx, (int) ly, (int) lz); if (between != null && !Orebfuscator.config.isBlockTransparent(between.getCombinedId())) { return false; // fail on first hit, this ray is "blocked" } s--; // we stop } return true; } private static void restart() { synchronized (thread) { if (thread.isInterrupted() || !thread.isAlive()) running = false; if (!running && Orebfuscator.config.isProximityHiderEnabled()) { // Load ProximityHider ProximityHider.Load(); } } } public static void addProximityBlocks(Player player, int chunkX, int chunkZ, ArrayList<BlockCoord> blocks) { ProximityHiderConfig proximityHider = Orebfuscator.configManager.getWorld(player.getWorld()).getProximityHiderConfig(); if (!proximityHider.isEnabled()) return; restart(); synchronized (proximityHiderTracker) { ProximityHiderPlayer playerInfo = proximityHiderTracker.get(player); World world = player.getWorld(); if (playerInfo == null) { proximityHiderTracker.put(player, playerInfo = new ProximityHiderPlayer(world)); } else if(!playerInfo.getWorld().equals(world)) { playerInfo.setWorld(world); playerInfo.clearChunks(); } if(blocks.size() > 0) { playerInfo.putBlocks(chunkX, chunkZ, blocks); } else { playerInfo.removeChunk(chunkX, chunkZ); } } boolean isPlayerToReload; synchronized (playersToReload) { isPlayerToReload = playersToReload.remove(player); } if(isPlayerToReload) { addPlayerToCheck(player, null); } } public static void clearPlayer(Player player) { synchronized (proximityHiderTracker) { proximityHiderTracker.remove(player); } synchronized (playersToCheck) { playersToCheck.remove(player); } synchronized (playersToReload) { playersToReload.remove(player); } } public static void clearBlocksForOldWorld(Player player) { synchronized (proximityHiderTracker) { ProximityHiderPlayer playerInfo = proximityHiderTracker.get(player); if(playerInfo != null) { World world = player.getWorld(); if(!playerInfo.getWorld().equals(world)) { playerInfo.setWorld(world); playerInfo.clearChunks(); } } } } public static void addPlayerToCheck(Player player, Location location) { synchronized (playersToCheck) { if (!playersToCheck.containsKey(player)) { playersToCheck.put(player, location); } } } public static void addPlayersToReload(HashSet<Player> players) { if (!Orebfuscator.config.isProximityHiderEnabled()) return; synchronized (playersToReload) { playersToReload.addAll(players); } } }
14,732
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
CalculationsUtil.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/obfuscation/CalculationsUtil.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.obfuscation; import java.util.zip.CRC32; public class CalculationsUtil { public static long Hash(byte[] data, int length) { CRC32 crc = new CRC32(); crc.reset(); crc.update(data, 0, length); return crc.getValue(); } public static int increment(int current, int max) { return (current + 1) % max; } }
1,044
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ProtocolLibHook.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/Plugin/src/main/java/com/lishid/orebfuscator/hook/ProtocolLibHook.java
/* * Copyright (C) 2011-2014 lishid. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.lishid.orebfuscator.hook; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; import com.comphenix.protocol.events.PacketAdapter; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.events.PacketEvent; import com.comphenix.protocol.reflect.StructureModifier; import com.comphenix.protocol.wrappers.EnumWrappers; import com.comphenix.protocol.wrappers.nbt.NbtCompound; import com.comphenix.protocol.wrappers.nbt.NbtFactory; import com.lishid.orebfuscator.Orebfuscator; import com.lishid.orebfuscator.chunkmap.ChunkData; import com.lishid.orebfuscator.config.WorldConfig; import com.lishid.orebfuscator.hithack.BlockHitManager; import com.lishid.orebfuscator.obfuscation.Calculations; import com.lishid.orebfuscator.types.BlockCoord; public class ProtocolLibHook { private ProtocolManager manager; public void register(Plugin plugin) { this.manager = ProtocolLibrary.getProtocolManager(); this.manager.addPacketListener(new PacketAdapter(plugin, PacketType.Play.Server.MAP_CHUNK) { @Override public void onPacketSending(PacketEvent event) { ChunkData chunkData = null; try { Player player = event.getPlayer(); if (!Orebfuscator.config.isEnabled() || !Orebfuscator.config.obfuscateForPlayer(player)) { return; } WorldConfig worldConfig = Orebfuscator.configManager.getWorld(player.getWorld()); if(!worldConfig.isEnabled()) { return; } PacketContainer packet = event.getPacket(); StructureModifier<Integer> ints = packet.getIntegers(); StructureModifier<byte[]> byteArray = packet.getByteArrays(); StructureModifier<Boolean> bools = packet.getBooleans(); StructureModifier<List> list = packet.getSpecificModifier(List.class); List nmsTags = list.read(0); chunkData = new ChunkData(); chunkData.chunkX = ints.read(0); chunkData.chunkZ = ints.read(1); chunkData.groundUpContinuous = bools.read(0); chunkData.primaryBitMask = ints.read(2); chunkData.data = byteArray.read(0); chunkData.isOverworld = event.getPlayer().getWorld().getEnvironment() == World.Environment.NORMAL; chunkData.blockEntities = getBlockEntities(nmsTags); Calculations.Result result = Calculations.obfuscateOrUseCache(chunkData, player, worldConfig); if(result != null && result.output != null) { byteArray.write(0, result.output); if(nmsTags != null) { removeBlockEntities(nmsTags, chunkData.blockEntities, result.removedEntities); list.write(0, nmsTags); } } } catch (Exception e) { if(chunkData != null) { Orebfuscator.logger.log(Level.SEVERE, "ChunkX = " + chunkData.chunkX + ", chunkZ = " + chunkData.chunkZ); } e.printStackTrace(); } } }); manager.addPacketListener(new PacketAdapter(plugin, PacketType.Play.Client.BLOCK_DIG) { @Override public void onPacketReceiving(PacketEvent event) { EnumWrappers.PlayerDigType status = event.getPacket().getPlayerDigTypes().read(0); if (status == EnumWrappers.PlayerDigType.ABORT_DESTROY_BLOCK) { if (!BlockHitManager.hitBlock(event.getPlayer(), null)) { event.setCancelled(true); } } } }); } @SuppressWarnings("rawtypes") private static List<NbtCompound> getBlockEntities(List nmsTags) { List<NbtCompound> entities = new ArrayList<>(); if(nmsTags != null) { for (Object nmsTag : nmsTags) { entities.add(NbtFactory.fromNMSCompound(nmsTag)); } } return entities; } @SuppressWarnings("rawtypes") private static void removeBlockEntities(List nmsTags, List<NbtCompound> tags, List<BlockCoord> removedEntities) { for(int i = nmsTags.size() - 1; i >= 0; i--) { if(removedEntities.size() == 0) { break; } NbtCompound tag = tags.get(i); int x = tag.getInteger("x"); int y = tag.getInteger("y"); int z = tag.getInteger("z"); for(int k = 0; k < removedEntities.size(); k++) { BlockCoord blockCoord = removedEntities.get(k); if(blockCoord.x == x && blockCoord.y == y && blockCoord.z == z) { nmsTags.remove(i); removedEntities.remove(k); break; } } } } /* private static boolean _isSaved; private void saveTestData(ChunkData chunkData) { if(_isSaved) return; _isSaved = true; FileOutputStream fos; try { fos = new FileOutputStream("D:\\Temp\\chunk_X" + chunkData.chunkX + "_Z" + chunkData.chunkZ + ".dat"); fos.write(chunkData.chunkX & 0xff); fos.write((chunkData.chunkX >> 8) & 0xff); fos.write(chunkData.chunkZ & 0xff); fos.write((chunkData.chunkZ >> 8) & 0xff); fos.write(chunkData.primaryBitMask & 0xff); fos.write((chunkData.primaryBitMask >> 8) & 0xff); fos.write(chunkData.data.length & 0xff); fos.write((chunkData.data.length >> 8) & 0xff); fos.write((chunkData.data.length >> 16) & 0xff); fos.write(chunkData.data); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } */ }
6,170
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NBT.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_12_R1/src/main/java/com/lishid/orebfuscator/nms/v1_12_R1/NBT.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_12_R1; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.IOException; import net.minecraft.server.v1_12_R1.NBTCompressedStreamTools; import net.minecraft.server.v1_12_R1.NBTTagCompound; import com.lishid.orebfuscator.nms.INBT; public class NBT implements INBT { NBTTagCompound nbt = new NBTTagCompound(); public void reset() { nbt = new NBTTagCompound(); } public void setInt(String tag, int value) { nbt.setInt(tag, value); } public void setLong(String tag, long value) { nbt.setLong(tag, value); } public void setByteArray(String tag, byte[] value) { nbt.setByteArray(tag, value); } public void setIntArray(String tag, int[] value) { nbt.setIntArray(tag, value); } public int getInt(String tag) { return nbt.getInt(tag); } public long getLong(String tag) { return nbt.getLong(tag); } public byte[] getByteArray(String tag) { return nbt.getByteArray(tag); } public int[] getIntArray(String tag) { return nbt.getIntArray(tag); } public void Read(DataInput stream) throws IOException { nbt = NBTCompressedStreamTools.a((DataInputStream) stream); } public void Write(DataOutput stream) throws IOException { NBTCompressedStreamTools.a(nbt, stream); } }
1,489
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NmsManager.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_12_R1/src/main/java/com/lishid/orebfuscator/nms/v1_12_R1/NmsManager.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_12_R1; import com.google.common.collect.ImmutableList; import com.lishid.orebfuscator.types.ConfigDefaults; import net.minecraft.server.v1_12_R1.*; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.craftbukkit.v1_12_R1.CraftWorld; import org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_12_R1.util.CraftChatMessage; import org.bukkit.entity.Player; import com.lishid.orebfuscator.nms.IBlockInfo; import com.lishid.orebfuscator.nms.IChunkCache; import com.lishid.orebfuscator.nms.INBT; import com.lishid.orebfuscator.nms.INmsManager; import com.lishid.orebfuscator.types.BlockCoord; import java.util.HashSet; import java.util.Set; public class NmsManager implements INmsManager { private ConfigDefaults configDefaults; private Material[] extraTransparentBlocks; private int maxLoadedCacheFiles; public NmsManager() { this.configDefaults = new ConfigDefaults(); // Default World this.configDefaults.defaultProximityHiderBlockIds = convertMaterialsToIds(new Material[] { Material.DISPENSER, Material.MOB_SPAWNER, Material.CHEST, Material.HOPPER, Material.WORKBENCH, Material.FURNACE, Material.BURNING_FURNACE, Material.ENCHANTMENT_TABLE, Material.EMERALD_ORE, Material.ENDER_CHEST, Material.ANVIL, Material.TRAPPED_CHEST, Material.DIAMOND_ORE }); this.configDefaults.defaultDarknessBlockIds = convertMaterialsToIds(new Material[] { Material.MOB_SPAWNER, Material.CHEST }); this.configDefaults.defaultMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.defaultProximityHiderSpecialBlockId = getMaterialIds(Material.STONE).iterator().next(); // The End this.configDefaults.endWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.BEDROCK, Material.OBSIDIAN, Material.ENDER_STONE, Material.PURPUR_BLOCK, Material.END_BRICKS }); this.configDefaults.endWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.ENDER_STONE }); this.configDefaults.endWorldMode1BlockId = getMaterialIds(Material.ENDER_STONE).iterator().next(); this.configDefaults.endWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.ENDER_STONE }); // Nether World this.configDefaults.netherWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.GRAVEL, Material.NETHERRACK, Material.SOUL_SAND, Material.NETHER_BRICK, Material.QUARTZ_ORE }); this.configDefaults.netherWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK, Material.QUARTZ_ORE }); this.configDefaults.netherWorldMode1BlockId = getMaterialIds(Material.NETHERRACK).iterator().next(); this.configDefaults.netherWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK }); // Normal World this.configDefaults.normalWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.STONE, Material.COBBLESTONE, Material.WOOD, Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.TNT, Material.MOSSY_COBBLESTONE, Material.OBSIDIAN, Material.DIAMOND_ORE, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.CHEST, Material.DIAMOND_ORE, Material.ENDER_CHEST, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.normalWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.STONE }); // Extra transparent blocks this.extraTransparentBlocks = new Material[] { Material.ACACIA_DOOR, Material.ACACIA_FENCE, Material.ACACIA_FENCE_GATE, Material.ACACIA_STAIRS, Material.ANVIL, Material.BEACON, Material.BED_BLOCK, Material.BIRCH_DOOR, Material.BIRCH_FENCE, Material.BIRCH_FENCE_GATE, Material.BIRCH_WOOD_STAIRS, Material.BREWING_STAND, Material.BRICK_STAIRS, Material.CACTUS, Material.CAKE_BLOCK, Material.CAULDRON, Material.COBBLESTONE_STAIRS, Material.COBBLE_WALL, Material.DARK_OAK_DOOR, Material.DARK_OAK_FENCE, Material.DARK_OAK_FENCE_GATE, Material.DARK_OAK_STAIRS, Material.DAYLIGHT_DETECTOR, Material.DAYLIGHT_DETECTOR_INVERTED, Material.DRAGON_EGG, Material.ENCHANTMENT_TABLE, Material.FENCE, Material.FENCE_GATE, Material.GLASS, Material.HOPPER, Material.ICE, Material.IRON_DOOR_BLOCK, Material.IRON_FENCE, Material.IRON_PLATE, Material.IRON_TRAPDOOR, Material.JUNGLE_DOOR, Material.JUNGLE_FENCE, Material.JUNGLE_FENCE_GATE, Material.JUNGLE_WOOD_STAIRS, Material.LAVA, Material.LEAVES, Material.LEAVES_2, Material.MOB_SPAWNER, Material.NETHER_BRICK_STAIRS, Material.NETHER_FENCE, Material.PACKED_ICE, Material.PISTON_BASE, Material.PISTON_EXTENSION, Material.PISTON_MOVING_PIECE, Material.PISTON_STICKY_BASE, Material.PURPUR_SLAB, Material.PURPUR_STAIRS, Material.QUARTZ_STAIRS, Material.RED_SANDSTONE_STAIRS, Material.SANDSTONE_STAIRS, Material.SIGN_POST, Material.SLIME_BLOCK, Material.SMOOTH_STAIRS, Material.SPRUCE_DOOR, Material.SPRUCE_FENCE, Material.SPRUCE_FENCE_GATE, Material.SPRUCE_WOOD_STAIRS, Material.STAINED_GLASS, Material.STAINED_GLASS_PANE, Material.STANDING_BANNER, Material.STATIONARY_LAVA, Material.STATIONARY_WATER, Material.STEP, Material.STONE_PLATE, Material.STONE_SLAB2, Material.THIN_GLASS, Material.TRAP_DOOR, Material.WALL_BANNER, Material.WALL_SIGN, Material.WATER, Material.WEB, Material.WOODEN_DOOR, Material.WOOD_PLATE, Material.WOOD_STAIRS, Material.WOOD_STEP }; } public ConfigDefaults getConfigDefaults() { return this.configDefaults; } public Material[] getExtraTransparentBlocks() { return this.extraTransparentBlocks; } public void setMaxLoadedCacheFiles(int value) { this.maxLoadedCacheFiles = value; } public INBT createNBT() { return new NBT(); } @Override public IChunkCache createChunkCache() { return new ChunkCache(this.maxLoadedCacheFiles); } @Override public void updateBlockTileEntity(BlockCoord blockCoord, Player player) { CraftWorld world = (CraftWorld)player.getWorld(); TileEntity tileEntity = world.getTileEntityAt(blockCoord.x, blockCoord.y, blockCoord.z); if (tileEntity == null) { return; } Packet<?> packet = tileEntity.getUpdatePacket(); if (packet != null) { CraftPlayer player2 = (CraftPlayer)player; player2.getHandle().playerConnection.sendPacket(packet); } } @Override public void notifyBlockChange(World world, IBlockInfo blockInfo) { BlockPosition blockPosition = new BlockPosition(blockInfo.getX(), blockInfo.getY(), blockInfo.getZ()); IBlockData blockData = ((BlockInfo)blockInfo).getBlockData(); ((CraftWorld)world).getHandle().notify(blockPosition, blockData, blockData, 0); } @Override public int getBlockLightLevel(World world, int x, int y, int z) { return ((CraftWorld)world).getHandle().getLightLevel(new BlockPosition(x, y, z)); } @Override public IBlockInfo getBlockInfo(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, false); return blockData != null ? new BlockInfo(x, y, z, blockData) : null; } @Override public int loadChunkAndGetBlockId(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, true); return blockData != null ? Block.getId(blockData.getBlock()): -1; } @Override public String getTextFromChatComponent(String json) { IChatBaseComponent component = IChatBaseComponent.ChatSerializer.a(json); return CraftChatMessage.fromComponent(component); } public boolean isHoe(Material item) { return item == Material.WOOD_HOE || item == Material.IRON_HOE || item == Material.GOLD_HOE || item == Material.DIAMOND_HOE; } @SuppressWarnings("deprecation") public boolean isSign(int combinedBlockId) { int typeId = combinedBlockId >> 4; return typeId == Material.WALL_SIGN.getId() || typeId == Material.SIGN_POST.getId(); } public boolean isAir(int combinedBlockId) { return combinedBlockId == 0; } public boolean isTileEntity(int combinedBlockId) { return Block.getByCombinedId(combinedBlockId).getBlock().isTileEntity(); } public int getCaveAirBlockId() { return 0; } public int getBitsPerBlock() { return 13; } public boolean canApplyPhysics(Material blockMaterial) { return blockMaterial == Material.AIR || blockMaterial == Material.FIRE || blockMaterial == Material.WATER || blockMaterial == Material.STATIONARY_WATER || blockMaterial == Material.LAVA || blockMaterial == Material.STATIONARY_LAVA; } @SuppressWarnings("deprecation") public Set<Integer> getMaterialIds(Material material) { Set<Integer> ids = new HashSet<>(); int blockId = material.getId() << 4; Block block = Block.getById(material.getId()); ImmutableList<IBlockData> blockDataList = block.s().a(); for(IBlockData blockData : blockDataList) { ids.add(blockId | block.toLegacyData(blockData)); } return ids; } @SuppressWarnings("deprecation") public boolean sendBlockChange(Player player, Location blockLocation) { IBlockData blockData = getBlockData(blockLocation.getWorld(), blockLocation.getBlockX(), blockLocation.getBlockY(), blockLocation.getBlockZ(), false); if(blockData == null) return false; Block block = blockData.getBlock(); int blockId = Block.getId(block); byte meta = (byte)block.toLegacyData(blockData); player.sendBlockChange(blockLocation, blockId, meta); return true; } private static IBlockData getBlockData(World world, int x, int y, int z, boolean loadChunk) { int chunkX = x >> 4; int chunkZ = z >> 4; WorldServer worldServer = ((CraftWorld)world).getHandle(); ChunkProviderServer chunkProviderServer = worldServer.getChunkProviderServer(); if(!loadChunk && !chunkProviderServer.isLoaded(chunkX, chunkZ)) return null; Chunk chunk = chunkProviderServer.getOrLoadChunkAt(chunkX, chunkZ); return chunk != null ? chunk.getBlockData(new BlockPosition(x, y, z)) : null; } private Set<Integer> convertMaterialsToSet(Material[] materials) { Set<Integer> ids = new HashSet<>(); for(Material material : materials) { ids.addAll(getMaterialIds(material)); } return ids; } private int[] convertMaterialsToIds(Material[] materials) { Set<Integer> ids = convertMaterialsToSet(materials); int[] result = new int[ids.size()]; int index = 0; for(int id : ids) { result[index++] = id; } return result; } }
11,354
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkCache.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_12_R1/src/main/java/com/lishid/orebfuscator/nms/v1_12_R1/ChunkCache.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_12_R1; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.util.HashMap; import net.minecraft.server.v1_12_R1.RegionFile; import com.lishid.orebfuscator.nms.IChunkCache; public class ChunkCache implements IChunkCache { private static final HashMap<File, RegionFile> cachedRegionFiles = new HashMap<File, RegionFile>(); private int maxLoadedCacheFiles; public ChunkCache(int maxLoadedCacheFiles) { this.maxLoadedCacheFiles = maxLoadedCacheFiles; } public DataInputStream getInputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.a(x & 0x1F, z & 0x1F); } public DataOutputStream getOutputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.b(x & 0x1F, z & 0x1F); } public void closeCacheFiles() { closeCacheFilesInternal(); } private synchronized RegionFile getRegionFile(File folder, int x, int z) { File path = new File(folder, "region"); File file = new File(path, "r." + (x >> 5) + "." + (z >> 5) + ".mcr"); try { RegionFile regionFile = cachedRegionFiles.get(file); if (regionFile != null) { return regionFile; } if (!path.exists()) { path.mkdirs(); } if (cachedRegionFiles.size() >= this.maxLoadedCacheFiles) { closeCacheFiles(); } regionFile = new RegionFile(file); cachedRegionFiles.put(file, regionFile); return regionFile; } catch (Exception e) { try { file.delete(); } catch (Exception e2) { } } return null; } private synchronized void closeCacheFilesInternal() { for (RegionFile regionFile : cachedRegionFiles.values()) { try { if (regionFile != null) regionFile.c(); } catch (Exception e) { e.printStackTrace(); } } cachedRegionFiles.clear(); } }
2,352
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
BlockInfo.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_12_R1/src/main/java/com/lishid/orebfuscator/nms/v1_12_R1/BlockInfo.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_12_R1; import net.minecraft.server.v1_12_R1.Block; import net.minecraft.server.v1_12_R1.IBlockData; import com.lishid.orebfuscator.nms.IBlockInfo; public class BlockInfo implements IBlockInfo { private int x; private int y; private int z; private IBlockData blockData; public BlockInfo(int x, int y, int z, IBlockData blockData) { this.x = x; this.y = y; this.z = z; this.blockData = blockData; } public int getX() { return this.x; } public int getY() { return this.y; } public int getZ() { return this.z; } public int getCombinedId() { Block block = this.blockData.getBlock(); return (Block.getId(block) << 4) | block.toLegacyData(this.blockData); } public IBlockData getBlockData() { return this.blockData; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof BlockInfo)) { return false; } BlockInfo object = (BlockInfo) other; return this.x == object.x && this.y == object.y && this.z == object.z; } @Override public int hashCode() { return this.x ^ this.y ^ this.z; } @Override public String toString() { return this.x + " " + this.y + " " + this.z; } }
1,253
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NBT.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_11_R1/src/main/java/com/lishid/orebfuscator/nms/v1_11_R1/NBT.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_11_R1; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.IOException; import net.minecraft.server.v1_11_R1.NBTCompressedStreamTools; import net.minecraft.server.v1_11_R1.NBTTagCompound; import com.lishid.orebfuscator.nms.INBT; public class NBT implements INBT { NBTTagCompound nbt = new NBTTagCompound(); public void reset() { nbt = new NBTTagCompound(); } public void setInt(String tag, int value) { nbt.setInt(tag, value); } public void setLong(String tag, long value) { nbt.setLong(tag, value); } public void setByteArray(String tag, byte[] value) { nbt.setByteArray(tag, value); } public void setIntArray(String tag, int[] value) { nbt.setIntArray(tag, value); } public int getInt(String tag) { return nbt.getInt(tag); } public long getLong(String tag) { return nbt.getLong(tag); } public byte[] getByteArray(String tag) { return nbt.getByteArray(tag); } public int[] getIntArray(String tag) { return nbt.getIntArray(tag); } public void Read(DataInput stream) throws IOException { nbt = NBTCompressedStreamTools.a((DataInputStream) stream); } public void Write(DataOutput stream) throws IOException { NBTCompressedStreamTools.a(nbt, stream); } }
1,489
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NmsManager.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_11_R1/src/main/java/com/lishid/orebfuscator/nms/v1_11_R1/NmsManager.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_11_R1; import com.google.common.collect.ImmutableList; import com.lishid.orebfuscator.types.ConfigDefaults; import net.minecraft.server.v1_11_R1.Block; import net.minecraft.server.v1_11_R1.BlockPosition; import net.minecraft.server.v1_11_R1.Chunk; import net.minecraft.server.v1_11_R1.ChunkProviderServer; import net.minecraft.server.v1_11_R1.IBlockData; import net.minecraft.server.v1_11_R1.IChatBaseComponent; import net.minecraft.server.v1_11_R1.Packet; import net.minecraft.server.v1_11_R1.TileEntity; import net.minecraft.server.v1_11_R1.WorldServer; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.craftbukkit.v1_11_R1.CraftWorld; import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_11_R1.util.CraftChatMessage; import org.bukkit.entity.Player; import com.lishid.orebfuscator.nms.IBlockInfo; import com.lishid.orebfuscator.nms.IChunkCache; import com.lishid.orebfuscator.nms.INBT; import com.lishid.orebfuscator.nms.INmsManager; import com.lishid.orebfuscator.types.BlockCoord; import java.util.HashSet; import java.util.Set; public class NmsManager implements INmsManager { private ConfigDefaults configDefaults; private Material[] extraTransparentBlocks; private int maxLoadedCacheFiles; public NmsManager() { this.configDefaults = new ConfigDefaults(); // Default World this.configDefaults.defaultProximityHiderBlockIds = convertMaterialsToIds(new Material[] { Material.DISPENSER, Material.MOB_SPAWNER, Material.CHEST, Material.HOPPER, Material.WORKBENCH, Material.FURNACE, Material.BURNING_FURNACE, Material.ENCHANTMENT_TABLE, Material.EMERALD_ORE, Material.ENDER_CHEST, Material.ANVIL, Material.TRAPPED_CHEST, Material.DIAMOND_ORE }); this.configDefaults.defaultDarknessBlockIds = convertMaterialsToIds(new Material[] { Material.MOB_SPAWNER, Material.CHEST }); this.configDefaults.defaultMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.defaultProximityHiderSpecialBlockId = getMaterialIds(Material.STONE).iterator().next(); // The End this.configDefaults.endWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.BEDROCK, Material.OBSIDIAN, Material.ENDER_STONE, Material.PURPUR_BLOCK, Material.END_BRICKS }); this.configDefaults.endWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.ENDER_STONE }); this.configDefaults.endWorldMode1BlockId = getMaterialIds(Material.ENDER_STONE).iterator().next(); this.configDefaults.endWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.ENDER_STONE }); // Nether World this.configDefaults.netherWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.GRAVEL, Material.NETHERRACK, Material.SOUL_SAND, Material.NETHER_BRICK, Material.QUARTZ_ORE }); this.configDefaults.netherWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK, Material.QUARTZ_ORE }); this.configDefaults.netherWorldMode1BlockId = getMaterialIds(Material.NETHERRACK).iterator().next(); this.configDefaults.netherWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK }); // Normal World this.configDefaults.normalWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.STONE, Material.COBBLESTONE, Material.WOOD, Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.TNT, Material.MOSSY_COBBLESTONE, Material.OBSIDIAN, Material.DIAMOND_ORE, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.CHEST, Material.DIAMOND_ORE, Material.ENDER_CHEST, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.normalWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.STONE }); // Extra transparent blocks this.extraTransparentBlocks = new Material[] { Material.ACACIA_DOOR, Material.ACACIA_FENCE, Material.ACACIA_FENCE_GATE, Material.ACACIA_STAIRS, Material.ANVIL, Material.BEACON, Material.BED_BLOCK, Material.BIRCH_DOOR, Material.BIRCH_FENCE, Material.BIRCH_FENCE_GATE, Material.BIRCH_WOOD_STAIRS, Material.BREWING_STAND, Material.BRICK_STAIRS, Material.CACTUS, Material.CAKE_BLOCK, Material.CAULDRON, Material.COBBLESTONE_STAIRS, Material.COBBLE_WALL, Material.DARK_OAK_DOOR, Material.DARK_OAK_FENCE, Material.DARK_OAK_FENCE_GATE, Material.DARK_OAK_STAIRS, Material.DAYLIGHT_DETECTOR, Material.DAYLIGHT_DETECTOR_INVERTED, Material.DRAGON_EGG, Material.ENCHANTMENT_TABLE, Material.FENCE, Material.FENCE_GATE, Material.GLASS, Material.HOPPER, Material.ICE, Material.IRON_DOOR_BLOCK, Material.IRON_FENCE, Material.IRON_PLATE, Material.IRON_TRAPDOOR, Material.JUNGLE_DOOR, Material.JUNGLE_FENCE, Material.JUNGLE_FENCE_GATE, Material.JUNGLE_WOOD_STAIRS, Material.LAVA, Material.LEAVES, Material.LEAVES_2, Material.MOB_SPAWNER, Material.NETHER_BRICK_STAIRS, Material.NETHER_FENCE, Material.PACKED_ICE, Material.PISTON_BASE, Material.PISTON_EXTENSION, Material.PISTON_MOVING_PIECE, Material.PISTON_STICKY_BASE, Material.PURPUR_SLAB, Material.PURPUR_STAIRS, Material.QUARTZ_STAIRS, Material.RED_SANDSTONE_STAIRS, Material.SANDSTONE_STAIRS, Material.SIGN_POST, Material.SLIME_BLOCK, Material.SMOOTH_STAIRS, Material.SPRUCE_DOOR, Material.SPRUCE_FENCE, Material.SPRUCE_FENCE_GATE, Material.SPRUCE_WOOD_STAIRS, Material.STAINED_GLASS, Material.STAINED_GLASS_PANE, Material.STANDING_BANNER, Material.STATIONARY_LAVA, Material.STATIONARY_WATER, Material.STEP, Material.STONE_PLATE, Material.STONE_SLAB2, Material.THIN_GLASS, Material.TRAP_DOOR, Material.WALL_BANNER, Material.WALL_SIGN, Material.WATER, Material.WEB, Material.WOODEN_DOOR, Material.WOOD_PLATE, Material.WOOD_STAIRS, Material.WOOD_STEP }; } public ConfigDefaults getConfigDefaults() { return this.configDefaults; } public Material[] getExtraTransparentBlocks() { return this.extraTransparentBlocks; } public void setMaxLoadedCacheFiles(int value) { this.maxLoadedCacheFiles = value; } public INBT createNBT() { return new NBT(); } @Override public IChunkCache createChunkCache() { return new ChunkCache(this.maxLoadedCacheFiles); } @Override public void updateBlockTileEntity(BlockCoord blockCoord, Player player) { CraftWorld world = (CraftWorld)player.getWorld(); TileEntity tileEntity = world.getTileEntityAt(blockCoord.x, blockCoord.y, blockCoord.z); if (tileEntity == null) { return; } Packet<?> packet = tileEntity.getUpdatePacket(); if (packet != null) { CraftPlayer player2 = (CraftPlayer)player; player2.getHandle().playerConnection.sendPacket(packet); } } @Override public void notifyBlockChange(World world, IBlockInfo blockInfo) { BlockPosition blockPosition = new BlockPosition(blockInfo.getX(), blockInfo.getY(), blockInfo.getZ()); IBlockData blockData = ((BlockInfo)blockInfo).getBlockData(); ((CraftWorld)world).getHandle().notify(blockPosition, blockData, blockData, 0); } @Override public int getBlockLightLevel(World world, int x, int y, int z) { return ((CraftWorld)world).getHandle().getLightLevel(new BlockPosition(x, y, z)); } @Override public IBlockInfo getBlockInfo(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, false); return blockData != null ? new BlockInfo(x, y, z, blockData) : null; } @Override public int loadChunkAndGetBlockId(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, true); return blockData != null ? Block.getId(blockData.getBlock()): -1; } @Override public String getTextFromChatComponent(String json) { IChatBaseComponent component = IChatBaseComponent.ChatSerializer.a(json); return CraftChatMessage.fromComponent(component); } public boolean isHoe(Material item) { return item == Material.WOOD_HOE || item == Material.IRON_HOE || item == Material.GOLD_HOE || item == Material.DIAMOND_HOE; } @SuppressWarnings("deprecation") public boolean isSign(int combinedBlockId) { int typeId = combinedBlockId >> 4; return typeId == Material.WALL_SIGN.getId() || typeId == Material.SIGN_POST.getId(); } public boolean isAir(int combinedBlockId) { return combinedBlockId == 0; } public boolean isTileEntity(int combinedBlockId) { return Block.getByCombinedId(combinedBlockId).getBlock().isTileEntity(); } public int getCaveAirBlockId() { return 0; } public int getBitsPerBlock() { return 13; } public boolean canApplyPhysics(Material blockMaterial) { return blockMaterial == Material.AIR || blockMaterial == Material.FIRE || blockMaterial == Material.WATER || blockMaterial == Material.STATIONARY_WATER || blockMaterial == Material.LAVA || blockMaterial == Material.STATIONARY_LAVA; } @SuppressWarnings("deprecation") public Set<Integer> getMaterialIds(Material material) { Set<Integer> ids = new HashSet<>(); int blockId = material.getId() << 4; Block block = Block.getById(material.getId()); ImmutableList<IBlockData> blockDataList = block.s().a(); for(IBlockData blockData : blockDataList) { ids.add(blockId | block.toLegacyData(blockData)); } return ids; } @SuppressWarnings("deprecation") public boolean sendBlockChange(Player player, Location blockLocation) { IBlockData blockData = getBlockData(blockLocation.getWorld(), blockLocation.getBlockX(), blockLocation.getBlockY(), blockLocation.getBlockZ(), false); if(blockData == null) return false; Block block = blockData.getBlock(); int blockId = Block.getId(block); byte meta = (byte)block.toLegacyData(blockData); player.sendBlockChange(blockLocation, blockId, meta); return true; } private static IBlockData getBlockData(World world, int x, int y, int z, boolean loadChunk) { int chunkX = x >> 4; int chunkZ = z >> 4; WorldServer worldServer = ((CraftWorld)world).getHandle(); ChunkProviderServer chunkProviderServer = worldServer.getChunkProviderServer(); if(!loadChunk && !chunkProviderServer.isLoaded(chunkX, chunkZ)) return null; Chunk chunk = chunkProviderServer.getOrLoadChunkAt(chunkX, chunkZ); return chunk != null ? chunk.getBlockData(new BlockPosition(x, y, z)) : null; } private Set<Integer> convertMaterialsToSet(Material[] materials) { Set<Integer> ids = new HashSet<>(); for(Material material : materials) { ids.addAll(getMaterialIds(material)); } return ids; } private int[] convertMaterialsToIds(Material[] materials) { Set<Integer> ids = convertMaterialsToSet(materials); int[] result = new int[ids.size()]; int index = 0; for(int id : ids) { result[index++] = id; } return result; } }
11,757
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkCache.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_11_R1/src/main/java/com/lishid/orebfuscator/nms/v1_11_R1/ChunkCache.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_11_R1; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.util.HashMap; import net.minecraft.server.v1_11_R1.RegionFile; import com.lishid.orebfuscator.nms.IChunkCache; public class ChunkCache implements IChunkCache { private static final HashMap<File, RegionFile> cachedRegionFiles = new HashMap<File, RegionFile>(); private int maxLoadedCacheFiles; public ChunkCache(int maxLoadedCacheFiles) { this.maxLoadedCacheFiles = maxLoadedCacheFiles; } public DataInputStream getInputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.a(x & 0x1F, z & 0x1F); } public DataOutputStream getOutputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.b(x & 0x1F, z & 0x1F); } public void closeCacheFiles() { closeCacheFilesInternal(); } private synchronized RegionFile getRegionFile(File folder, int x, int z) { File path = new File(folder, "region"); File file = new File(path, "r." + (x >> 5) + "." + (z >> 5) + ".mcr"); try { RegionFile regionFile = cachedRegionFiles.get(file); if (regionFile != null) { return regionFile; } if (!path.exists()) { path.mkdirs(); } if (cachedRegionFiles.size() >= this.maxLoadedCacheFiles) { closeCacheFiles(); } regionFile = new RegionFile(file); cachedRegionFiles.put(file, regionFile); return regionFile; } catch (Exception e) { try { file.delete(); } catch (Exception e2) { } } return null; } private synchronized void closeCacheFilesInternal() { for (RegionFile regionFile : cachedRegionFiles.values()) { try { if (regionFile != null) regionFile.c(); } catch (Exception e) { e.printStackTrace(); } } cachedRegionFiles.clear(); } }
2,352
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
BlockInfo.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_11_R1/src/main/java/com/lishid/orebfuscator/nms/v1_11_R1/BlockInfo.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_11_R1; import net.minecraft.server.v1_11_R1.Block; import net.minecraft.server.v1_11_R1.IBlockData; import com.lishid.orebfuscator.nms.IBlockInfo; public class BlockInfo implements IBlockInfo { private int x; private int y; private int z; private IBlockData blockData; public BlockInfo(int x, int y, int z, IBlockData blockData) { this.x = x; this.y = y; this.z = z; this.blockData = blockData; } public int getX() { return this.x; } public int getY() { return this.y; } public int getZ() { return this.z; } public int getCombinedId() { Block block = this.blockData.getBlock(); return (Block.getId(block) << 4) | block.toLegacyData(this.blockData); } public IBlockData getBlockData() { return this.blockData; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof BlockInfo)) { return false; } BlockInfo object = (BlockInfo) other; return this.x == object.x && this.y == object.y && this.z == object.z; } @Override public int hashCode() { return this.x ^ this.y ^ this.z; } @Override public String toString() { return this.x + " " + this.y + " " + this.z; } }
1,253
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NBT.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_9_R1/src/main/java/com/lishid/orebfuscator/nms/v1_9_R1/NBT.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_9_R1; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.IOException; import net.minecraft.server.v1_9_R1.NBTCompressedStreamTools; import net.minecraft.server.v1_9_R1.NBTTagCompound; import com.lishid.orebfuscator.nms.INBT; public class NBT implements INBT { NBTTagCompound nbt = new NBTTagCompound(); public void reset() { nbt = new NBTTagCompound(); } public void setInt(String tag, int value) { nbt.setInt(tag, value); } public void setLong(String tag, long value) { nbt.setLong(tag, value); } public void setByteArray(String tag, byte[] value) { nbt.setByteArray(tag, value); } public void setIntArray(String tag, int[] value) { nbt.setIntArray(tag, value); } public int getInt(String tag) { return nbt.getInt(tag); } public long getLong(String tag) { return nbt.getLong(tag); } public byte[] getByteArray(String tag) { return nbt.getByteArray(tag); } public int[] getIntArray(String tag) { return nbt.getIntArray(tag); } public void Read(DataInput stream) throws IOException { nbt = NBTCompressedStreamTools.a((DataInputStream) stream); } public void Write(DataOutput stream) throws IOException { NBTCompressedStreamTools.a(nbt, stream); } }
1,485
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
NmsManager.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_9_R1/src/main/java/com/lishid/orebfuscator/nms/v1_9_R1/NmsManager.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_9_R1; import com.google.common.collect.ImmutableList; import com.lishid.orebfuscator.types.ConfigDefaults; import net.minecraft.server.v1_9_R1.Block; import net.minecraft.server.v1_9_R1.BlockPosition; import net.minecraft.server.v1_9_R1.Chunk; import net.minecraft.server.v1_9_R1.ChunkProviderServer; import net.minecraft.server.v1_9_R1.IBlockData; import net.minecraft.server.v1_9_R1.IChatBaseComponent; import net.minecraft.server.v1_9_R1.Packet; import net.minecraft.server.v1_9_R1.TileEntity; import net.minecraft.server.v1_9_R1.WorldServer; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.craftbukkit.v1_9_R1.CraftWorld; import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_9_R1.util.CraftChatMessage; import org.bukkit.entity.Player; import com.lishid.orebfuscator.nms.IBlockInfo; import com.lishid.orebfuscator.nms.IChunkCache; import com.lishid.orebfuscator.nms.INBT; import com.lishid.orebfuscator.nms.INmsManager; import com.lishid.orebfuscator.types.BlockCoord; import java.util.HashSet; import java.util.Set; public class NmsManager implements INmsManager { private ConfigDefaults configDefaults; private Material[] extraTransparentBlocks; private int maxLoadedCacheFiles; public NmsManager() { this.configDefaults = new ConfigDefaults(); // Default World this.configDefaults.defaultProximityHiderBlockIds = convertMaterialsToIds(new Material[] { Material.DISPENSER, Material.MOB_SPAWNER, Material.CHEST, Material.HOPPER, Material.WORKBENCH, Material.FURNACE, Material.BURNING_FURNACE, Material.ENCHANTMENT_TABLE, Material.EMERALD_ORE, Material.ENDER_CHEST, Material.ANVIL, Material.TRAPPED_CHEST, Material.DIAMOND_ORE }); this.configDefaults.defaultDarknessBlockIds = convertMaterialsToIds(new Material[] { Material.MOB_SPAWNER, Material.CHEST }); this.configDefaults.defaultMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.defaultProximityHiderSpecialBlockId = getMaterialIds(Material.STONE).iterator().next(); // The End this.configDefaults.endWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.BEDROCK, Material.OBSIDIAN, Material.ENDER_STONE, Material.PURPUR_BLOCK, Material.END_BRICKS }); this.configDefaults.endWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.ENDER_STONE }); this.configDefaults.endWorldMode1BlockId = getMaterialIds(Material.ENDER_STONE).iterator().next(); this.configDefaults.endWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.ENDER_STONE }); // Nether World this.configDefaults.netherWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.GRAVEL, Material.NETHERRACK, Material.SOUL_SAND, Material.NETHER_BRICK, Material.QUARTZ_ORE }); this.configDefaults.netherWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK, Material.QUARTZ_ORE }); this.configDefaults.netherWorldMode1BlockId = getMaterialIds(Material.NETHERRACK).iterator().next(); this.configDefaults.netherWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.NETHERRACK }); // Normal World this.configDefaults.normalWorldRandomBlockIds = convertMaterialsToIds(new Material[] { Material.STONE, Material.COBBLESTONE, Material.WOOD, Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.TNT, Material.MOSSY_COBBLESTONE, Material.OBSIDIAN, Material.DIAMOND_ORE, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.GOLD_ORE, Material.IRON_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.CHEST, Material.DIAMOND_ORE, Material.ENDER_CHEST, Material.REDSTONE_ORE, Material.CLAY, Material.EMERALD_ORE }); this.configDefaults.normalWorldMode1BlockId = getMaterialIds(Material.STONE).iterator().next(); this.configDefaults.normalWorldRequiredObfuscateBlockIds = convertMaterialsToIds(new Material[] { Material.STONE }); // Extra transparent blocks this.extraTransparentBlocks = new Material[] { Material.ACACIA_DOOR, Material.ACACIA_FENCE, Material.ACACIA_FENCE_GATE, Material.ACACIA_STAIRS, Material.ANVIL, Material.BEACON, Material.BED_BLOCK, Material.BIRCH_DOOR, Material.BIRCH_FENCE, Material.BIRCH_FENCE_GATE, Material.BIRCH_WOOD_STAIRS, Material.BREWING_STAND, Material.BRICK_STAIRS, Material.CACTUS, Material.CAKE_BLOCK, Material.CAULDRON, Material.COBBLESTONE_STAIRS, Material.COBBLE_WALL, Material.DARK_OAK_DOOR, Material.DARK_OAK_FENCE, Material.DARK_OAK_FENCE_GATE, Material.DARK_OAK_STAIRS, Material.DAYLIGHT_DETECTOR, Material.DAYLIGHT_DETECTOR_INVERTED, Material.DRAGON_EGG, Material.ENCHANTMENT_TABLE, Material.FENCE, Material.FENCE_GATE, Material.GLASS, Material.HOPPER, Material.ICE, Material.IRON_DOOR_BLOCK, Material.IRON_FENCE, Material.IRON_PLATE, Material.IRON_TRAPDOOR, Material.JUNGLE_DOOR, Material.JUNGLE_FENCE, Material.JUNGLE_FENCE_GATE, Material.JUNGLE_WOOD_STAIRS, Material.LAVA, Material.LEAVES, Material.LEAVES_2, Material.MOB_SPAWNER, Material.NETHER_BRICK_STAIRS, Material.NETHER_FENCE, Material.PACKED_ICE, Material.PISTON_BASE, Material.PISTON_EXTENSION, Material.PISTON_MOVING_PIECE, Material.PISTON_STICKY_BASE, Material.PURPUR_SLAB, Material.PURPUR_STAIRS, Material.QUARTZ_STAIRS, Material.RED_SANDSTONE_STAIRS, Material.SANDSTONE_STAIRS, Material.SIGN_POST, Material.SLIME_BLOCK, Material.SMOOTH_STAIRS, Material.SPRUCE_DOOR, Material.SPRUCE_FENCE, Material.SPRUCE_FENCE_GATE, Material.SPRUCE_WOOD_STAIRS, Material.STAINED_GLASS, Material.STAINED_GLASS_PANE, Material.STANDING_BANNER, Material.STATIONARY_LAVA, Material.STATIONARY_WATER, Material.STEP, Material.STONE_PLATE, Material.STONE_SLAB2, Material.THIN_GLASS, Material.TRAP_DOOR, Material.WALL_BANNER, Material.WALL_SIGN, Material.WATER, Material.WEB, Material.WOODEN_DOOR, Material.WOOD_PLATE, Material.WOOD_STAIRS, Material.WOOD_STEP }; } public ConfigDefaults getConfigDefaults() { return this.configDefaults; } public Material[] getExtraTransparentBlocks() { return this.extraTransparentBlocks; } public void setMaxLoadedCacheFiles(int value) { this.maxLoadedCacheFiles = value; } public INBT createNBT() { return new NBT(); } public IChunkCache createChunkCache() { return new ChunkCache(this.maxLoadedCacheFiles); } public void updateBlockTileEntity(BlockCoord blockCoord, Player player) { CraftWorld world = (CraftWorld)player.getWorld(); TileEntity tileEntity = world.getTileEntityAt(blockCoord.x, blockCoord.y, blockCoord.z); if (tileEntity == null) { return; } Packet<?> packet = tileEntity.getUpdatePacket(); if (packet != null) { CraftPlayer player2 = (CraftPlayer)player; player2.getHandle().playerConnection.sendPacket(packet); } } public void notifyBlockChange(World world, IBlockInfo blockInfo) { BlockPosition blockPosition = new BlockPosition(blockInfo.getX(), blockInfo.getY(), blockInfo.getZ()); IBlockData blockData = ((BlockInfo)blockInfo).getBlockData(); ((CraftWorld)world).getHandle().notify(blockPosition, blockData, blockData, 0); } public int getBlockLightLevel(World world, int x, int y, int z) { return ((CraftWorld)world).getHandle().getLightLevel(new BlockPosition(x, y, z)); } public IBlockInfo getBlockInfo(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, false); return blockData != null ? new BlockInfo(x, y, z, blockData) : null; } public int loadChunkAndGetBlockId(World world, int x, int y, int z) { IBlockData blockData = getBlockData(world, x, y, z, true); return blockData != null ? Block.getCombinedId(blockData): -1; } public String getTextFromChatComponent(String json) { IChatBaseComponent component = IChatBaseComponent.ChatSerializer.a(json); return CraftChatMessage.fromComponent(component); } public boolean isHoe(Material item) { return item == Material.WOOD_HOE || item == Material.IRON_HOE || item == Material.GOLD_HOE || item == Material.DIAMOND_HOE; } @SuppressWarnings("deprecation") public boolean isSign(int combinedBlockId) { int typeId = combinedBlockId >> 4; return typeId == Material.WALL_SIGN.getId() || typeId == Material.SIGN_POST.getId(); } public boolean isAir(int combinedBlockId) { return combinedBlockId == 0; } public boolean isTileEntity(int combinedBlockId) { return Block.getByCombinedId(combinedBlockId).getBlock().isTileEntity(); } public int getCaveAirBlockId() { return 0; } public int getBitsPerBlock() { return 13; } public boolean canApplyPhysics(Material blockMaterial) { return blockMaterial == Material.AIR || blockMaterial == Material.FIRE || blockMaterial == Material.WATER || blockMaterial == Material.STATIONARY_WATER || blockMaterial == Material.LAVA || blockMaterial == Material.STATIONARY_LAVA; } @SuppressWarnings("deprecation") public Set<Integer> getMaterialIds(Material material) { Set<Integer> ids = new HashSet<>(); int blockId = material.getId() << 4; Block block = Block.getById(material.getId()); ImmutableList<IBlockData> blockDataList = block.t().a(); for(IBlockData blockData : blockDataList) { ids.add(blockId | block.toLegacyData(blockData)); } return ids; } @SuppressWarnings("deprecation") public boolean sendBlockChange(Player player, Location blockLocation) { IBlockData blockData = getBlockData(blockLocation.getWorld(), blockLocation.getBlockX(), blockLocation.getBlockY(), blockLocation.getBlockZ(), false); if(blockData == null) return false; Block block = blockData.getBlock(); int blockId = Block.getId(block); byte meta = (byte)block.toLegacyData(blockData); player.sendBlockChange(blockLocation, blockId, meta); return true; } private static IBlockData getBlockData(World world, int x, int y, int z, boolean loadChunk) { int chunkX = x >> 4; int chunkZ = z >> 4; WorldServer worldServer = ((CraftWorld)world).getHandle(); ChunkProviderServer chunkProviderServer = worldServer.getChunkProviderServer(); if(!loadChunk && !chunkProviderServer.isChunkLoaded(chunkX, chunkZ)) return null; Chunk chunk = chunkProviderServer.getOrLoadChunkAt(chunkX, chunkZ); return chunk != null ? chunk.getBlockData(new BlockPosition(x, y, z)) : null; } private Set<Integer> convertMaterialsToSet(Material[] materials) { Set<Integer> ids = new HashSet<>(); for(Material material : materials) { ids.addAll(getMaterialIds(material)); } return ids; } private int[] convertMaterialsToIds(Material[] materials) { Set<Integer> ids = convertMaterialsToSet(materials); int[] result = new int[ids.size()]; int index = 0; for(int id : ids) { result[index++] = id; } return result; } }
11,669
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
ChunkCache.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_9_R1/src/main/java/com/lishid/orebfuscator/nms/v1_9_R1/ChunkCache.java
/** * @author lishid * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_9_R1; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.util.HashMap; import net.minecraft.server.v1_9_R1.RegionFile; import com.lishid.orebfuscator.nms.IChunkCache; public class ChunkCache implements IChunkCache { private static final HashMap<File, RegionFile> cachedRegionFiles = new HashMap<File, RegionFile>(); private int maxLoadedCacheFiles; public ChunkCache(int maxLoadedCacheFiles) { this.maxLoadedCacheFiles = maxLoadedCacheFiles; } public DataInputStream getInputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.a(x & 0x1F, z & 0x1F); } public DataOutputStream getOutputStream(File folder, int x, int z) { RegionFile regionFile = getRegionFile(folder, x, z); return regionFile.b(x & 0x1F, z & 0x1F); } public void closeCacheFiles() { closeCacheFilesInternal(); } private synchronized RegionFile getRegionFile(File folder, int x, int z) { File path = new File(folder, "region"); File file = new File(path, "r." + (x >> 5) + "." + (z >> 5) + ".mcr"); try { RegionFile regionFile = cachedRegionFiles.get(file); if (regionFile != null) { return regionFile; } if (!path.exists()) { path.mkdirs(); } if (cachedRegionFiles.size() >= this.maxLoadedCacheFiles) { closeCacheFiles(); } regionFile = new RegionFile(file); cachedRegionFiles.put(file, regionFile); return regionFile; } catch (Exception e) { try { file.delete(); } catch (Exception e2) { } } return null; } private synchronized void closeCacheFilesInternal() { for (RegionFile regionFile : cachedRegionFiles.values()) { try { if (regionFile != null) regionFile.c(); } catch (Exception e) { e.printStackTrace(); } } cachedRegionFiles.clear(); } }
2,349
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
BlockInfo.java
/FileExtraction/Java_unseen/lishid_Orebfuscator/v1_9_R1/src/main/java/com/lishid/orebfuscator/nms/v1_9_R1/BlockInfo.java
/** * @author Aleksey Terzi * */ package com.lishid.orebfuscator.nms.v1_9_R1; import net.minecraft.server.v1_9_R1.Block; import net.minecraft.server.v1_9_R1.IBlockData; import com.lishid.orebfuscator.nms.IBlockInfo; public class BlockInfo implements IBlockInfo { private int x; private int y; private int z; private IBlockData blockData; public BlockInfo(int x, int y, int z, IBlockData blockData) { this.x = x; this.y = y; this.z = z; this.blockData = blockData; } public int getX() { return this.x; } public int getY() { return this.y; } public int getZ() { return this.z; } public int getCombinedId() { Block block = this.blockData.getBlock(); return (Block.getId(block) << 4) | block.toLegacyData(this.blockData); } public IBlockData getBlockData() { return this.blockData; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof BlockInfo)) { return false; } BlockInfo object = (BlockInfo) other; return this.x == object.x && this.y == object.y && this.z == object.z; } @Override public int hashCode() { return this.x ^ this.y ^ this.z; } @Override public String toString() { return this.x + " " + this.y + " " + this.z; } }
1,247
Java
.java
lishid/Orebfuscator
115
112
55
2011-09-24T23:34:43Z
2021-06-18T03:14:27Z
VelocityDiscordSRV.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/velocity/src/main/java/com/discordsrv/velocity/VelocityDiscordSRV.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.velocity; import com.discordsrv.common.ProxyDiscordSRV; import com.discordsrv.common.command.game.handler.ICommandHandler; import com.discordsrv.common.config.configurate.manager.ConnectionConfigManager; import com.discordsrv.common.config.configurate.manager.MainConfigManager; import com.discordsrv.common.config.configurate.manager.MessagesConfigManager; import com.discordsrv.common.config.connection.ConnectionConfig; import com.discordsrv.common.config.main.MainConfig; import com.discordsrv.common.config.messages.MessagesConfig; import com.discordsrv.common.debug.data.OnlineMode; import com.discordsrv.common.plugin.PluginManager; import com.discordsrv.common.scheduler.StandardScheduler; import com.discordsrv.velocity.command.game.handler.VelocityCommandHandler; import com.discordsrv.velocity.console.VelocityConsole; import com.discordsrv.velocity.player.VelocityPlayerProvider; import com.discordsrv.velocity.plugin.VelocityPluginManager; import com.velocitypowered.api.plugin.PluginContainer; import com.velocitypowered.api.proxy.ProxyServer; import org.jetbrains.annotations.NotNull; import java.net.URL; import java.net.URLClassLoader; import java.util.jar.JarFile; public class VelocityDiscordSRV extends ProxyDiscordSRV<DiscordSRVVelocityBootstrap, MainConfig, ConnectionConfig, MessagesConfig> { private final StandardScheduler scheduler; private final VelocityConsole console; private final VelocityPlayerProvider playerProvider; private final VelocityPluginManager pluginManager; private final VelocityCommandHandler commandHandler; public VelocityDiscordSRV(DiscordSRVVelocityBootstrap bootstrap) { super(bootstrap); this.scheduler = new StandardScheduler(this); this.console = new VelocityConsole(this); this.playerProvider = new VelocityPlayerProvider(this); this.pluginManager = new VelocityPluginManager(this); this.commandHandler = new VelocityCommandHandler(this); load(); } @Override protected URL getManifest() { ClassLoader classLoader = getClass().getClassLoader(); if (classLoader instanceof URLClassLoader) { return ((URLClassLoader) classLoader).findResource(JarFile.MANIFEST_NAME); } else { throw new IllegalStateException("Class not loaded by a URLClassLoader, unable to get manifest"); } } public Object plugin() { return bootstrap; } public PluginContainer container() { return bootstrap.pluginContainer(); } public ProxyServer proxy() { return bootstrap.proxyServer(); } @Override public StandardScheduler scheduler() { return scheduler; } @Override public VelocityConsole console() { return console; } @Override public @NotNull VelocityPlayerProvider playerProvider() { return playerProvider; } @Override public PluginManager pluginManager() { return pluginManager; } @Override public OnlineMode onlineMode() { return OnlineMode.of(proxy().getConfiguration().isOnlineMode()); } @Override public ICommandHandler commandHandler() { return commandHandler; } @Override public ConnectionConfigManager<ConnectionConfig> connectionConfigManager() { return null; } @Override public MainConfigManager<MainConfig> configManager() { return null; } @Override public MessagesConfigManager<MessagesConfig> messagesConfigManager() { return null; } @Override protected void enable() throws Throwable { super.enable(); } }
4,522
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordSRVVelocityBootstrap.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/velocity/src/main/java/com/discordsrv/velocity/DiscordSRVVelocityBootstrap.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.velocity; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.bootstrap.IBootstrap; import com.discordsrv.common.bootstrap.LifecycleManager; import com.discordsrv.common.logging.Logger; import com.discordsrv.common.logging.backend.impl.SLF4JLoggerImpl; import com.google.inject.Inject; import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; import com.velocitypowered.api.event.proxy.ProxyReloadEvent; import com.velocitypowered.api.event.proxy.ProxyShutdownEvent; import com.velocitypowered.api.plugin.Plugin; import com.velocitypowered.api.plugin.PluginContainer; import com.velocitypowered.api.plugin.annotation.DataDirectory; import com.velocitypowered.api.proxy.ProxyServer; import dev.vankka.dependencydownload.classpath.ClasspathAppender; import dev.vankka.mcdependencydownload.velocity.classpath.VelocityClasspathAppender; import java.io.IOException; import java.nio.file.Path; @Plugin( id = "discordsrv", name = "DiscordSRV", version = "@VERSION@", description = "", authors = {"Scarsz", "Vankka"}, url = DiscordSRV.WEBSITE ) public class DiscordSRVVelocityBootstrap implements IBootstrap { private final Logger logger; private final ClasspathAppender classpathAppender; private final LifecycleManager lifecycleManager; private final ProxyServer proxyServer; private final PluginContainer pluginContainer; private final Path dataDirectory; private VelocityDiscordSRV discordSRV; @Inject public DiscordSRVVelocityBootstrap(com.discordsrv.unrelocate.org.slf4j.Logger logger, ProxyServer proxyServer, PluginContainer pluginContainer, @DataDirectory Path dataDirectory) throws IOException { this.logger = new SLF4JLoggerImpl(logger); this.classpathAppender = new VelocityClasspathAppender(this, proxyServer); this.lifecycleManager = new LifecycleManager( this.logger, dataDirectory, new String[] {"dependencies/runtimeDownload-velocity.txt"}, classpathAppender ); this.proxyServer = proxyServer; this.pluginContainer = pluginContainer; this.dataDirectory = dataDirectory; } @Subscribe public void onProxyInitialize(ProxyInitializeEvent event) { lifecycleManager.loadAndEnable(() -> this.discordSRV = new VelocityDiscordSRV(this)); } @Subscribe public void onProxyReload(ProxyReloadEvent event) { lifecycleManager.reload(discordSRV); } @Subscribe public void onProxyShutdown(ProxyShutdownEvent event) { lifecycleManager.disable(discordSRV); } @Override public Logger logger() { return logger; } @Override public ClasspathAppender classpathAppender() { return classpathAppender; } @Override public ClassLoader classLoader() { return getClass().getClassLoader(); } @Override public LifecycleManager lifecycleManager() { return lifecycleManager; } @Override public Path dataDirectory() { return dataDirectory; } public ProxyServer proxyServer() { return proxyServer; } public PluginContainer pluginContainer() { return pluginContainer; } }
4,185
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
VelocityCommandHandler.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/velocity/src/main/java/com/discordsrv/velocity/command/game/handler/VelocityCommandHandler.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.velocity.command.game.handler; import com.discordsrv.common.command.game.abstraction.GameCommand; import com.discordsrv.common.command.game.handler.ICommandHandler; import com.discordsrv.common.command.game.handler.util.BrigadierUtil; import com.discordsrv.common.command.game.sender.ICommandSender; import com.discordsrv.velocity.VelocityDiscordSRV; import com.discordsrv.velocity.command.game.sender.VelocityCommandSender; import com.mojang.brigadier.tree.LiteralCommandNode; import com.velocitypowered.api.command.BrigadierCommand; import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.proxy.ConsoleCommandSource; import com.velocitypowered.api.proxy.Player; public class VelocityCommandHandler implements ICommandHandler { private final VelocityDiscordSRV discordSRV; public VelocityCommandHandler(VelocityDiscordSRV discordSRV) { this.discordSRV = discordSRV; } private ICommandSender getSender(CommandSource source) { if (source instanceof Player) { return discordSRV.playerProvider().player((Player) source); } else if (source instanceof ConsoleCommandSource) { return discordSRV.console(); } else { return new VelocityCommandSender(discordSRV, source); } } @Override public void registerCommand(GameCommand command) { LiteralCommandNode<CommandSource> node = BrigadierUtil.convertToBrigadier(command, this::getSender); discordSRV.proxy().getCommandManager().register(new BrigadierCommand(node)); } }
2,422
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
VelocityCommandSender.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/velocity/src/main/java/com/discordsrv/velocity/command/game/sender/VelocityCommandSender.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.velocity.command.game.sender; import com.discordsrv.common.command.game.sender.ICommandSender; import com.discordsrv.velocity.VelocityDiscordSRV; import com.velocitypowered.api.command.CommandSource; import net.kyori.adventure.audience.Audience; import org.jetbrains.annotations.NotNull; public class VelocityCommandSender implements ICommandSender { protected final VelocityDiscordSRV discordSRV; protected final CommandSource commandSource; public VelocityCommandSender(VelocityDiscordSRV discordSRV, CommandSource commandSource) { this.discordSRV = discordSRV; this.commandSource = commandSource; } @Override public boolean hasPermission(String permission) { return commandSource.hasPermission(permission); } @Override public void runCommand(String command) { discordSRV.proxy().getCommandManager().executeAsync(commandSource, command); } @Override public @NotNull Audience audience() { return commandSource; } }
1,868
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
VelocityPluginManager.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/velocity/src/main/java/com/discordsrv/velocity/plugin/VelocityPluginManager.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.velocity.plugin; import com.discordsrv.common.plugin.Plugin; import com.discordsrv.common.plugin.PluginManager; import com.discordsrv.velocity.VelocityDiscordSRV; import com.velocitypowered.api.plugin.PluginDescription; import java.util.List; import java.util.stream.Collectors; public class VelocityPluginManager implements PluginManager { private final VelocityDiscordSRV discordSRV; public VelocityPluginManager(VelocityDiscordSRV discordSRV) { this.discordSRV = discordSRV; } @Override public boolean isPluginEnabled(String pluginName) { return discordSRV.proxy().getPluginManager().isLoaded(pluginName); } @Override public List<Plugin> getPlugins() { return discordSRV.proxy().getPluginManager().getPlugins().stream() .map(container -> { PluginDescription description = container.getDescription(); String id = description.getId(); return new Plugin( id, description.getName().orElse(id), description.getVersion().orElse("Unknown"), description.getAuthors() ); }) .collect(Collectors.toList()); } }
2,163
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
VelocityConsole.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/velocity/src/main/java/com/discordsrv/velocity/console/VelocityConsole.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.velocity.console; import com.discordsrv.common.command.game.executor.CommandExecutorProvider; import com.discordsrv.common.console.Console; import com.discordsrv.common.logging.backend.LoggingBackend; import com.discordsrv.common.logging.backend.impl.Log4JLoggerImpl; import com.discordsrv.velocity.VelocityDiscordSRV; import com.discordsrv.velocity.command.game.sender.VelocityCommandSender; import com.discordsrv.velocity.console.executor.VelocityCommandExecutorProvider; public class VelocityConsole extends VelocityCommandSender implements Console { private final LoggingBackend loggingBackend; private final VelocityCommandExecutorProvider executorProvider; public VelocityConsole(VelocityDiscordSRV discordSRV) { super(discordSRV, discordSRV.proxy().getConsoleCommandSource()); this.loggingBackend = Log4JLoggerImpl.getRoot(); this.executorProvider = new VelocityCommandExecutorProvider(discordSRV); } @Override public LoggingBackend loggingBackend() { return loggingBackend; } @Override public CommandExecutorProvider commandExecutorProvider() { return executorProvider; } }
2,021
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
VelocityCommandExecutor.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/velocity/src/main/java/com/discordsrv/velocity/console/executor/VelocityCommandExecutor.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.velocity.console.executor; import com.discordsrv.common.command.game.executor.AdventureCommandExecutorProxy; import com.discordsrv.common.command.game.executor.CommandExecutor; import com.discordsrv.velocity.VelocityDiscordSRV; import com.velocitypowered.api.proxy.ConsoleCommandSource; import net.kyori.adventure.text.Component; import java.util.function.Consumer; public class VelocityCommandExecutor implements CommandExecutor { private final VelocityDiscordSRV discordSRV; private final ConsoleCommandSource source; public VelocityCommandExecutor(VelocityDiscordSRV discordSRV, Consumer<Component> componentConsumer) { this.discordSRV = discordSRV; this.source = (ConsoleCommandSource) new AdventureCommandExecutorProxy( discordSRV.proxy().getConsoleCommandSource(), componentConsumer ).getProxy(); } @Override public void runCommand(String command) { discordSRV.proxy().getCommandManager().executeAsync(source, command); } }
1,881
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
VelocityCommandExecutorProvider.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/velocity/src/main/java/com/discordsrv/velocity/console/executor/VelocityCommandExecutorProvider.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.velocity.console.executor; import com.discordsrv.common.command.game.executor.CommandExecutor; import com.discordsrv.common.command.game.executor.CommandExecutorProvider; import com.discordsrv.velocity.VelocityDiscordSRV; import net.kyori.adventure.text.Component; import java.util.function.Consumer; public class VelocityCommandExecutorProvider implements CommandExecutorProvider { private final VelocityDiscordSRV discordSRV; public VelocityCommandExecutorProvider(VelocityDiscordSRV discordSRV) { this.discordSRV = discordSRV; } @Override public CommandExecutor getConsoleExecutor(Consumer<Component> componentConsumer) { return new VelocityCommandExecutor(discordSRV, componentConsumer); } }
1,595
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
VelocityPlayer.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/velocity/src/main/java/com/discordsrv/velocity/player/VelocityPlayer.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.velocity.player; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.player.IPlayer; import com.discordsrv.common.player.provider.model.SkinInfo; import com.discordsrv.common.player.provider.model.Textures; import com.discordsrv.velocity.VelocityDiscordSRV; import com.discordsrv.velocity.command.game.sender.VelocityCommandSender; import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.util.GameProfile; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Locale; public class VelocityPlayer extends VelocityCommandSender implements IPlayer { private final Player player; public VelocityPlayer(VelocityDiscordSRV discordSRV, Player player) { super(discordSRV, player); this.player = player; } @Override public DiscordSRV discordSRV() { return discordSRV; } @Override public @NotNull String username() { return player.getUsername(); } @Override public @Nullable SkinInfo skinInfo() { for (GameProfile.Property property : player.getGameProfile().getProperties()) { if (!Textures.KEY.equals(property.getName())) { continue; } Textures textures = Textures.getFromBase64(discordSRV, property.getValue()); return textures.getSkinInfo(); } return null; } @Override public @Nullable Locale locale() { return player.getPlayerSettings().getLocale(); } @Override public @NotNull Identity identity() { return player.identity(); } @Override public @NotNull Component displayName() { // Use Adventure's Pointer, otherwise username return player.getOrDefaultFrom( Identity.DISPLAY_NAME, () -> Component.text(player.getUsername()) ); } }
2,842
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z