mirror of
https://github.com/proxiodev/RedisBungee.git
synced 2026-05-03 03:30:26 +00:00
Compare commits
151 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 265933f36e | |||
|
|
9a583369e8 | ||
|
|
d9e5a21c14 | ||
|
|
4f43c98c87 | ||
| 26b58252eb | |||
|
|
73879640e5 | ||
|
|
c5040c9348 | ||
|
|
9ca72ff921 | ||
| 9050264b4d | |||
|
|
5b5f748cc9 | ||
|
|
47127c8520 | ||
|
|
b857bdb771 | ||
| 0f0f707ef7 | |||
| 441a12bb36 | |||
|
|
0534970368 | ||
| 20f9143ea5 | |||
| 1a2459b64e | |||
|
|
c3888c8f65 | ||
| c8362a44ec | |||
| 31e461a11c | |||
| a9ea04c2c0 | |||
| ddfc689c2d | |||
| ae6961ef24 | |||
| 8318bcd1bf | |||
| 0b9fd6d7ff | |||
| a526298d1c | |||
| c69b1e214e | |||
| e5f0075a58 | |||
| 748bc13568 | |||
| 5e3ce725de | |||
| 92bb0030de | |||
| d8c21edc7a | |||
| 87a2b93537 | |||
| 0f5d5b2440 | |||
| 21f543581c | |||
| bc266ae1fa | |||
| 8dc42d071a | |||
| 71b959936e | |||
| 28419b3168 | |||
| a382a298a1 | |||
| 4d58ee1742 | |||
| af4e180b2c | |||
| c1ad902bd3 | |||
| 74ed18e9b3 | |||
| a51ff98909 | |||
| 80a4791d12 | |||
| fdd537b276 | |||
| 17897bc112 | |||
| 576bcc39d2 | |||
| 508125023e | |||
| 43b2d20e39 | |||
| 64af12044e | |||
| 2ae9b5d480 | |||
| d77e909e7d | |||
| ee76fa0b3d | |||
|
|
f303f2c202 | ||
|
|
4e46dc5536 | ||
|
|
b58e503ec7 | ||
|
|
b16a7d4cbc | ||
| 5a7001a68c | |||
| 81a8fd218e | |||
| 92f5e04edf | |||
| e7b241edd6 | |||
| 86c6e9464d | |||
| 1828cd854c | |||
| 6910c96f67 | |||
| 8f602407b5 | |||
| 2c4fc00ec3 | |||
| 11e867730c | |||
| 830077282d | |||
| 2b2ae88587 | |||
| 9ceccb6dd2 | |||
| dea384a203 | |||
| e4012a8d7b | |||
| 2c8c5fc1cf | |||
| 5c6cf405fa | |||
| 0408e2923b | |||
| 5d1167c20f | |||
| 79694fcbb2 | |||
| 1d889f28b9 | |||
| f274301036 | |||
| c787c76eca | |||
| 9da5845da3 | |||
| 4d3f1a551e | |||
| 17e6e12c24 | |||
| c207b4a0a2 | |||
| c848126aa7 | |||
| f722b8c9d3 | |||
| d806bc2d41 | |||
| 2e8342f5c3 | |||
|
|
c125137a74 | ||
| aff185a85b | |||
| 482dfc5141 | |||
| 6a6e303334 | |||
| a9600a7d8a | |||
| 36136d0c0f | |||
| 319b5eb553 | |||
| 38de948c6b | |||
| 019bb30c09 | |||
| f1f74b6456 | |||
| b0ab5e3cb4 | |||
| b214e3dad7 | |||
| 81a2af8179 | |||
| b910fa5eb6 | |||
| b15b9dbb96 | |||
| 44f9a0945d | |||
| e986d5f1fb | |||
| ce93bd5e07 | |||
| 870e6113db | |||
| 86b0904546 | |||
| f4dbb00991 | |||
| b6e4badc05 | |||
| 78ae6ff7b6 | |||
| 87aaf22073 | |||
| a74e4b6a15 | |||
| d6d8c30343 | |||
| 933fceba9d | |||
| a8b369dde3 | |||
| 414f29e99c | |||
|
|
21f6cdeaeb | ||
| 5f07ba6b66 | |||
| 673b966dda | |||
| 69d435d455 | |||
| 3a8baae56f | |||
| 803ae36d00 | |||
| ceef1f5184 | |||
| cd4f2aded4 | |||
| d8a220bcc2 | |||
|
|
c3d23a3601 | ||
|
|
ea600c5b44 | ||
| 86f2d89cf4 | |||
| 70d1aadd56 | |||
| 183c227b77 | |||
| 640b26067a | |||
| 660bb239bb | |||
| dd9c9e368d | |||
| 76787455d8 | |||
| 2c11cb179a | |||
| 9f05bd3438 | |||
|
|
c04a911fbe | ||
| 0311a893c7 | |||
| 5a51d5c1b3 | |||
| afac7a3d51 | |||
| bdda99bc81 | |||
| ea665fd70f | |||
| f7285ff4f1 | |||
|
|
28d1667fe9 | ||
|
|
839c8cd615 | ||
|
|
83dff6b280 | ||
|
|
0b868ffd6f | ||
|
|
d7c8544b99 |
2
.github/ISSUE_TEMPLATE/bug_report.md
vendored
2
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -2,7 +2,7 @@
|
||||
name: Bug report
|
||||
about: if you find a bug please report it here...
|
||||
title: ''
|
||||
labels: waiting.....
|
||||
labels: waiting
|
||||
assignees: ham1255
|
||||
|
||||
---
|
||||
|
||||
26
.github/workflows/maven.yml
vendored
26
.github/workflows/maven.yml
vendored
@@ -5,9 +5,9 @@ name: RedisBungee Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
branches: [ develop ]
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
branches: [ develop ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -19,14 +19,24 @@ jobs:
|
||||
- name: Set up JDK 11
|
||||
uses: actions/setup-java@v2
|
||||
with:
|
||||
java-version: '8'
|
||||
java-version: '11'
|
||||
distribution: 'adopt'
|
||||
- name: Build with Maven
|
||||
run: mvn -B package --file pom.xml
|
||||
- name: Download a Build Artifact
|
||||
- name: Build with gradle
|
||||
run: ./gradlew shadowJar
|
||||
- name: Upload Bungee
|
||||
uses: actions/upload-artifact@v2.2.3
|
||||
with:
|
||||
# Artifact name
|
||||
name: Redis_JAR
|
||||
name: RedisBungee-Bungee
|
||||
# Destination path
|
||||
path: target/RedisBungee*
|
||||
path: RedisBungee-Bungee/build/libs/*
|
||||
- name: Upload Velocity
|
||||
uses: actions/upload-artifact@v2.2.3
|
||||
with:
|
||||
name: RedisBungee-Velocity
|
||||
path: RedisBungee-Velocity/build/libs/*
|
||||
- name: Upload API
|
||||
uses: actions/upload-artifact@v2.2.3
|
||||
with:
|
||||
name: RedisBungee-API
|
||||
path: RedisBungee-API/build/libs/*
|
||||
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -39,5 +39,11 @@ manifest.mf
|
||||
|
||||
*.versionBackup
|
||||
*.versionsBackup
|
||||
# gradle
|
||||
.gradle
|
||||
|
||||
# java docs
|
||||
javadoc
|
||||
|
||||
# run-server folders
|
||||
*/run
|
||||
|
||||
178
README.md
178
README.md
@@ -1,46 +1,48 @@
|
||||
# RedisBungee fork By Limework
|
||||
|
||||
Spigot link: [click](https://www.spigotmc.org/resources/redisbungee.87700/)
|
||||
*if you are here for transferring players to another proxy when the first proxy crashes or whatever this plugin won't do it, tell mojang to implement transfer packet*.
|
||||
[Click here, for more information about transfer packet](https://hypixel.net/threads/why-do-we-need-transfer-packets.1390307/)
|
||||
|
||||
The main project of RedisBungee is no longer maintained, so we have forked the plugin.
|
||||
The original project of RedisBungee is no longer maintained, so we have forked the plugin.
|
||||
RedisBungee uses [Redis](https://redis.io) with Java client [Jedis](https://github.com/redis/jedis/)
|
||||
to Synchronize players data between [BungeeCord](https://github.com/SpigotMC/BungeeCord) or [Velocity*](https://github.com/PaperMC/Velocity) proxies
|
||||
|
||||
RedisBungee uses [Redis](https://redis.io) to Synchronize data between [BungeeCord](https://github.com/SpigotMC/BungeeCord) proxies
|
||||
Velocity*: *version 3.1.2 or above is only supported, any version below that might work but might be unstable* [#40](https://github.com/ProxioDev/RedisBungee/pull/40)
|
||||
|
||||
## Downloads
|
||||
[](https://modrinth.com/plugin/redisbungee)
|
||||
|
||||
or from github releases
|
||||
|
||||
https://github.com/ProxioDev/RedisBungee/releases
|
||||
|
||||
## notes
|
||||
If you are looking to use Original RedisBungee without a change to internals,
|
||||
with critical bugs fixed, please use version [0.6.5](https://github.com/ProxioDev/RedisBungee/releases/tag/0.6.5) and java docs For legacy Version [0.6.5](https://proxiodev.github.io/RedisBungee-JavaDocs/0.6.5-SNAPSHOT/)
|
||||
as its last version before internal changes. please note that you will not get support for any old builds unless critical bugs effecting both 0.6.5 and 0.7.0 or above.
|
||||
|
||||
SpigotMC resource page: [click](https://www.spigotmc.org/resources/redisbungee.87700/)
|
||||
## Supported Redis versions
|
||||
| Redis version | Supported |
|
||||
|:-------------:|:---------:|
|
||||
| 1.x.x | ✖ |
|
||||
| 2.x.x | ✖ |
|
||||
| 3.x.x | ✖ |
|
||||
| 4.x.x | ✖ |
|
||||
| 5.x.x | ✖ |
|
||||
| 3.x.x | ✔ |
|
||||
| 4.x.x | ✔ |
|
||||
| 5.x.x | ✔ |
|
||||
| 6.x.x | ✔ |
|
||||
| 7.x.x | ✔ |
|
||||
|
||||
|
||||
## Implementing RedisBungee in your plugin: [](https://github.com/Limework/RedisBungee/actions/workflows/maven.yml) [](https://jitpack.io/#limework/redisbungee)
|
||||
## Implementing RedisBungee in your plugin: [](https://github.com/Limework/RedisBungee/actions/workflows/maven.yml) [](https://jitpack.io/#ProxioDev/redisbungee)
|
||||
|
||||
RedisBungee is distributed as a [maven](https://maven.apache.org) project.
|
||||
RedisBungee is distributed as a [Gradle](https://gradle.org/) project.
|
||||
|
||||
first, install it to your maven local repo as we don't have public maven repo.
|
||||
```
|
||||
git clone https://github.com/ProxioDev/RedisBungee.git
|
||||
cd RedisBungee
|
||||
mvn clean install
|
||||
```
|
||||
then to import for bungeecord use:
|
||||
```
|
||||
<dependency>
|
||||
<groupId>com.imaginarycode.minecraft</groupId>
|
||||
<artifactId>RedisBungee-Bungee</artifactId>
|
||||
<version>0.7.2-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
```
|
||||
Second method by using jitpack [](https://jitpack.io/#limework/redisbungee)
|
||||
By using jitpack [](https://jitpack.io/#ProxioDev/redisbungee)
|
||||
|
||||
first, add this repository
|
||||
```
|
||||
# Setup jitpack repository
|
||||
## maven
|
||||
```xml
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>jitpack.io</id>
|
||||
@@ -48,36 +50,129 @@ first, add this repository
|
||||
</repository>
|
||||
</repositories>
|
||||
```
|
||||
then add this in your dependencies
|
||||
## gradle (kotlin dsl)
|
||||
```kotlin
|
||||
repositories {
|
||||
maven("https://jitpack.io/")
|
||||
}
|
||||
```
|
||||
|
||||
# [BungeeCord](https://github.com/SpigotMC/BungeeCord)
|
||||
add this in your project dependencies
|
||||
## maven
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>com.github.limework.redisbungee</groupId>
|
||||
<groupId>com.github.proxiodev.redisbungee</groupId>
|
||||
<artifactId>RedisBungee-Bungee</artifactId>
|
||||
<version>0.7.2</version>
|
||||
<version>VERSION</version>
|
||||
<scope>provided</scope>
|
||||
<!-- <classifier>all</classifier> USE THIS IF YOU WANT TO USE INCLUDED JEDIS LIB BECAUSE OF RELOCATION -->
|
||||
</dependency>
|
||||
|
||||
```
|
||||
## gradle (kotlin dsl)
|
||||
```
|
||||
implementation("com.github.ProxioDev.redisbungee:RedisBungee-Bungee:0.11.0")
|
||||
|
||||
## Notice 2: users on git.limework.net
|
||||
// USE THIS IF YOU WANT TO USE INCLUDED JEDIS LIB BECAUSE OF RELOACTION AND REMOVE THE ABOVE STATEMENT
|
||||
implementation("com.github.ProxioDev.redisbungee:RedisBungee-Bungee:0.11.0:all") {
|
||||
exclude("redis.clients", "jedis")
|
||||
}
|
||||
```
|
||||
then in your project plugin.yml add `RedisBungee` to `depends` like this
|
||||
```yaml
|
||||
name: "yourplugin"
|
||||
main: your.main.class
|
||||
version: 1.0.0-SNAPSHOT
|
||||
author: idk
|
||||
depends: [ RedisBungee ]
|
||||
```
|
||||
|
||||
please create the issues on GitHub as its main project source.
|
||||
|
||||
## [Velocity](https://github.com/PaperMC/Velocity)
|
||||
## maven
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>com.github.proxiodev.redisbungee</groupId>
|
||||
<artifactId>RedisBungee-Velocity</artifactId>
|
||||
<version>VERSION</version>
|
||||
<scope>provided</scope>
|
||||
<!-- <classifier>all</classifier> USE THIS IF YOU WANT TO USE INCLUDED JEDIS LIB BECAUSE OF RELOCATION -->
|
||||
</dependency>
|
||||
```
|
||||
## gradle (kotlin dsl)
|
||||
```
|
||||
implementation("com.github.ProxioDev.redisbungee:RedisBungee-Velocity:0.11.0")
|
||||
|
||||
// USE THIS IF YOU WANT TO USE INCLUDED JEDIS LIB BECAUSE OF RELOACTION AND REMOVE THE ABOVE STATEMENT
|
||||
implementation("com.github.ProxioDev.redisbungee:RedisBungee-Velocity:0.11.0:all") {
|
||||
exclude("redis.clients", "jedis")
|
||||
}
|
||||
```
|
||||
|
||||
then to make your plugin depends on RedisBungee, make sure your plugin class Annotation have `@Dependency(id = "redisbungee")` like this
|
||||
```java
|
||||
@Plugin(
|
||||
id = "myplugin",
|
||||
name = "My Plugin",
|
||||
version = "0.1.0-beta",
|
||||
dependencies = {
|
||||
@Dependency(id = "redisbungee")
|
||||
}
|
||||
)
|
||||
public class PluginMainClass {
|
||||
|
||||
}
|
||||
```
|
||||
## Getting the latest commits to your code
|
||||
If you want to use the latest commits without waiting for releases.
|
||||
first, install it to your maven local repo
|
||||
```bash
|
||||
git clone https://github.com/ProxioDev/RedisBungee.git
|
||||
cd RedisBungee
|
||||
./gradlew publishToMavenLocal
|
||||
```
|
||||
then use any of these in your project.
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>com.imaginarycode.minecraft</groupId>
|
||||
<artifactId>RedisBungee-Bungee</artifactId>
|
||||
<version>VERSION</version>
|
||||
<scope>provided</scope>
|
||||
<!-- <classifier>all</classifier> USE THIS IF YOU WANT TO USE INCLUDED JEDIS LIB BECAUSE OF RELOCATION -->
|
||||
</dependency>
|
||||
```
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>com.imaginarycode.minecraft</groupId>
|
||||
<artifactId>RedisBungee-Velocity</artifactId>
|
||||
<version>VERSION</version>
|
||||
<scope>provided</scope>
|
||||
<!-- <classifier>all</classifier> USE THIS IF YOU WANT TO USE INCLUDED JEDIS LIB BECAUSE OF RELOCATION -->
|
||||
</dependency>
|
||||
```
|
||||
## Javadocs
|
||||
|
||||
https://proxiodev.github.io/RedisBungee-JavaDocs/0.7.2-SNAPSHOT
|
||||
* API: https://ci.limework.net/RedisBungee/RedisBungee-API/build/docs/javadoc/
|
||||
* Velocity: https://ci.limework.net/RedisBungee/RedisBungee-Velocity/build/docs/javadoc/
|
||||
* Bungeecord: https://ci.limework.net/RedisBungee/RedisBungee-Bungee/build/docs/javadoc/
|
||||
|
||||
## Configuration
|
||||
|
||||
**REDISBUNGEE REQUIRES A REDIS SERVER**, preferably with reasonably low latency. The default [config](https://github.com/proxiodev/RedisBungee/blob/master/src/main/resources/example_config.yml) is saved when the plugin first starts.
|
||||
**REDISBUNGEE REQUIRES A REDIS SERVER**, preferably with reasonably low latency. The default [config](https://github.com/ProxioDev/RedisBungee/blob/develop/RedisBungee-API/src/main/resources/config.yml) is saved when the plugin first starts.
|
||||
|
||||
## License!
|
||||
|
||||
This project is distributed under Eclipse Public License 1.0
|
||||
## compatibility with original RedisBungee in Bungeecord ecosystem
|
||||
This fork ensures compatibility with old plugins, so it should work as drop replacement,
|
||||
but since Api has been split from the platform there some changes that have to be done, so your plugin might not work if:
|
||||
|
||||
You can find it [here](https://github.com/proxiodev/RedisBungee/blob/master/LICENSE)
|
||||
* there is none at the moment, please report any findings at the issue page.
|
||||
|
||||
You can find the original RedisBungee by minecrafter [here](https://github.com/minecrafter/RedisBungee) or spigot page [here](https://www.spigotmc.org/resources/redisbungee.13494/)
|
||||
Cluster mode compatibility in version 0.8.0:
|
||||
|
||||
If you are using static legacy method `RedisBungee#getPool()` it might fail in:
|
||||
* if Cluster mode is enabled, due fact its Uses different classes
|
||||
* if JedisPool compatibility mode is disabled in the config due fact project internally switched to JedisPooled than Jedis
|
||||
|
||||
## Support
|
||||
|
||||
@@ -85,6 +180,15 @@ You can join our matrix room [here](https://matrix.to/#/!zhedzmRNSZXfuOPZUB:govi
|
||||
|
||||

|
||||
|
||||
## License
|
||||
|
||||
This project is distributed under Eclipse Public License 1.0
|
||||
|
||||
You can find it [here](https://github.com/proxiodev/RedisBungee/blob/master/LICENSE)
|
||||
|
||||
You can find the original RedisBungee is by [astei](https://github.com/astei) and project can be found [here](https://github.com/minecrafter/RedisBungee) or spigot page [here, but its no longer available](https://www.spigotmc.org/resources/redisbungee.13494/)
|
||||
|
||||
|
||||
|
||||
## YourKit
|
||||
|
||||
|
||||
88
RedisBungee-API/build.gradle.kts
Normal file
88
RedisBungee-API/build.gradle.kts
Normal file
@@ -0,0 +1,88 @@
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
plugins {
|
||||
`java-library`
|
||||
`maven-publish`
|
||||
id("net.kyori.blossom") version "1.2.0"
|
||||
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
|
||||
val jedisVersion = "4.3.2"
|
||||
val configurateVersion = "3.7.3"
|
||||
val guavaVersion = "31.1-jre"
|
||||
|
||||
|
||||
dependencies {
|
||||
api("com.google.guava:guava:$guavaVersion")
|
||||
api("redis.clients:jedis:$jedisVersion")
|
||||
api("com.squareup.okhttp:okhttp:2.7.5")
|
||||
api("org.spongepowered:configurate-yaml:$configurateVersion")
|
||||
|
||||
// tests
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
|
||||
description = "RedisBungee interafaces"
|
||||
|
||||
blossom {
|
||||
replaceToken("@version@", "$version")
|
||||
// GIT
|
||||
var commit: String = ""
|
||||
val commitStdout = ByteArrayOutputStream()
|
||||
rootProject.exec {
|
||||
standardOutput = commitStdout
|
||||
commandLine("git", "rev-parse", "HEAD")
|
||||
}
|
||||
commit = "$commitStdout".replace("\n", "") // for some reason it adds new line so remove it.
|
||||
commitStdout.close()
|
||||
replaceToken("@git_commit@", commit)
|
||||
}
|
||||
|
||||
java {
|
||||
withJavadocJar()
|
||||
withSourcesJar()
|
||||
}
|
||||
|
||||
tasks {
|
||||
// thanks again for paper too
|
||||
withType<Javadoc> {
|
||||
val options = options as StandardJavadocDocletOptions
|
||||
options.use()
|
||||
options.isDocFilesSubDirs = true
|
||||
options.links(
|
||||
"https://configurate.aoeu.xyz/$configurateVersion/apidocs/", // configurate
|
||||
"https://javadoc.io/doc/redis.clients/jedis/$jedisVersion/", // jedis
|
||||
"https://guava.dev/releases/$guavaVersion/api/docs/" // guava
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
compileJava {
|
||||
options.encoding = Charsets.UTF_8.name()
|
||||
options.release.set(8)
|
||||
}
|
||||
javadoc {
|
||||
options.encoding = Charsets.UTF_8.name()
|
||||
|
||||
}
|
||||
processResources {
|
||||
filteringCharset = Charsets.UTF_8.name()
|
||||
}
|
||||
}
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
create<MavenPublication>("maven") {
|
||||
from(components["java"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>RedisBungee</artifactId>
|
||||
<groupId>com.imaginarycode.minecraft</groupId>
|
||||
<version>0.7.3-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>RedisBungee-API</artifactId>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>3.3.2</version>
|
||||
<configuration>
|
||||
<source>8</source>
|
||||
<reportOutputDirectory>../javadoc</reportOutputDirectory>
|
||||
<destDir>${project.name}</destDir>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!--
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.2.4</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<configuration>
|
||||
<relocations>
|
||||
<relocation>
|
||||
<pattern>redis.clients.jedis</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.jedis
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>redis.clients.util</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.jedisutil
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>org.apache.commons.pool</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.commonspool
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>com.squareup.okhttp</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.okhttp
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>okio</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.okio
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>com.google</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.google
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>org.json</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.json
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>org.checkerframework</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.checkframework
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
</relocations>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
-->
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -1,39 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.RedisBungeePlugin;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeeMode;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.summoners.JedisClusterSummoner;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.summoners.JedisPooledSummoner;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.summoners.Summoner;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisCluster;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.JedisPooled;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This class exposes some internal RedisBungee functions. You obtain an instance of this object by invoking {@link RedisBungeeAPI#getRedisBungeeApi()}
|
||||
* or somehow you got the Plugin instance by you can call the api using {@link RedisBungeePlugin#getApi()}.
|
||||
*
|
||||
* @author tuxed
|
||||
* @since 0.2.3 | updated 0.7.0
|
||||
* This abstract class is extended by platform plugin to provide some platform specific methods.
|
||||
* overall its general contains all methods needed by external usage.
|
||||
*
|
||||
* @author Ham1255
|
||||
* @since 0.8.0
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public class RedisBungeeAPI {
|
||||
private final RedisBungeePlugin<?> plugin;
|
||||
private final List<String> reservedChannels;
|
||||
private static RedisBungeeAPI redisBungeeApi;
|
||||
public abstract class AbstractRedisBungeeAPI {
|
||||
protected final RedisBungeePlugin<?> plugin;
|
||||
private static AbstractRedisBungeeAPI abstractRedisBungeeAPI;
|
||||
protected final List<String> reservedChannels;
|
||||
|
||||
RedisBungeeAPI(RedisBungeePlugin<?> plugin) {
|
||||
this.plugin = plugin;
|
||||
redisBungeeApi = this;
|
||||
AbstractRedisBungeeAPI(RedisBungeePlugin<?> plugin) {
|
||||
// this does make sure that no one can place first initiated API class.
|
||||
if (abstractRedisBungeeAPI == null) {
|
||||
abstractRedisBungeeAPI = this;
|
||||
}
|
||||
this.reservedChannels = ImmutableList.of(
|
||||
"redisbungee-allservers",
|
||||
"redisbungee-" + plugin.getConfiguration().getServerId(),
|
||||
"redisbungee-" + plugin.getConfiguration().getProxyId(),
|
||||
"redisbungee-data"
|
||||
);
|
||||
|
||||
this.plugin = plugin;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,10 +81,11 @@ public class RedisBungeeAPI {
|
||||
* Get the server where the specified player is playing. This function also deals with the case of local players
|
||||
* as well, and will return local information on them.
|
||||
*
|
||||
* @param player a player name
|
||||
* @return a String name for the server the player is on.
|
||||
* @param player a player uuid
|
||||
* @return a String name for the server the player is on. Can be Null if plugins is doing weird stuff to the proxy internals
|
||||
*/
|
||||
public final String getServerFor(@NonNull UUID player) {
|
||||
@Nullable
|
||||
public final String getServerNameFor(@NonNull UUID player) {
|
||||
return plugin.getDataManager().getServer(player);
|
||||
}
|
||||
|
||||
@@ -100,7 +122,7 @@ public class RedisBungeeAPI {
|
||||
* @since 0.2.5
|
||||
*/
|
||||
public final Multimap<String, UUID> getServerToPlayers() {
|
||||
return plugin.serversToPlayers();
|
||||
return plugin.serverToPlayersCache();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -171,8 +193,8 @@ public class RedisBungeeAPI {
|
||||
*
|
||||
* @param proxyId a proxy ID
|
||||
* @param command the command to send and execute
|
||||
* @see #getServerId()
|
||||
* @see #getAllServers()
|
||||
* @see #getProxyId()
|
||||
* @see #getAllProxies()
|
||||
* @since 0.2.5
|
||||
*/
|
||||
public final void sendProxyCommand(@NonNull String proxyId, @NonNull String command) {
|
||||
@@ -192,14 +214,38 @@ public class RedisBungeeAPI {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current BungeeCord server ID for this server.
|
||||
* Get the current BungeeCord / Velocity proxy ID for this server.
|
||||
*
|
||||
* @return the current server ID
|
||||
* @see #getAllProxies()
|
||||
* @since 0.8.0
|
||||
*/
|
||||
public final String getProxyId() {
|
||||
return plugin.getConfiguration().getProxyId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current BungeeCord / Velocity proxy ID for this server.
|
||||
*
|
||||
* @return the current server ID
|
||||
* @see #getAllServers()
|
||||
* @since 0.2.5
|
||||
* @deprecated to avoid confusion between A server and A proxy see #getProxyId()
|
||||
*/
|
||||
@Deprecated
|
||||
public final String getServerId() {
|
||||
return plugin.getConfiguration().getServerId();
|
||||
return getProxyId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the linked proxies in this network.
|
||||
*
|
||||
* @return the list of all proxies
|
||||
* @see #getProxyId()
|
||||
* @since 0.8.0
|
||||
*/
|
||||
public final List<String> getAllProxies() {
|
||||
return plugin.getProxiesIds();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -208,9 +254,11 @@ public class RedisBungeeAPI {
|
||||
* @return the list of all proxies
|
||||
* @see #getServerId()
|
||||
* @since 0.2.5
|
||||
* @deprecated to avoid confusion between A server and A proxy see see {@link #getAllProxies()}
|
||||
*/
|
||||
@Deprecated
|
||||
public final List<String> getAllServers() {
|
||||
return plugin.getServerIds();
|
||||
return getAllProxies();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -234,7 +282,7 @@ public class RedisBungeeAPI {
|
||||
Preconditions.checkArgument(!reservedChannels.contains(channel), "attempting to unregister internal channel");
|
||||
}
|
||||
|
||||
plugin.getPubSubListener().removeChannel(channels);
|
||||
plugin.getPubSubListener().removeChannel(channels);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -305,35 +353,119 @@ public class RedisBungeeAPI {
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* This gets Redis Bungee {@link JedisPool}
|
||||
* @return {@link JedisPool}
|
||||
* @deprecated this secluded to be removed when support for redis sentinel or redis cluster is finished, use {@link RedisBungeeAPI#requestJedis()}
|
||||
* @since 0.6.5
|
||||
* Kicks a player from the network
|
||||
*
|
||||
* @param playerName player name
|
||||
* @param message kick message that player will see on kick
|
||||
* @since 0.8.0
|
||||
*/
|
||||
@Deprecated
|
||||
public JedisPool getJedisPool() {
|
||||
return this.plugin.getJedisPool();
|
||||
|
||||
public void kickPlayer(String playerName, String message) {
|
||||
plugin.kickPlayer(playerName, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kicks a player from the network
|
||||
*
|
||||
* @param playerUUID player name
|
||||
* @param message kick message that player will see on kick
|
||||
* @since 0.8.0
|
||||
*/
|
||||
public void kickPlayer(UUID playerUUID, String message) {
|
||||
plugin.kickPlayer(playerUUID, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* This gives you instance of Jedis
|
||||
*
|
||||
* @return {@link Jedis}
|
||||
* @throws IllegalStateException if the {@link #getMode()} is not equal to {@link RedisBungeeMode#SINGLE}
|
||||
* @see #getJedisPool()
|
||||
* @since 0.7.0
|
||||
*/
|
||||
public Jedis requestJedis() {
|
||||
return this.plugin.requestJedis();
|
||||
if (getMode() == RedisBungeeMode.SINGLE) {
|
||||
return getJedisPool().getResource();
|
||||
} else {
|
||||
throw new IllegalStateException("Mode is not " + RedisBungeeMode.SINGLE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This gets Redis Bungee {@link JedisPool}
|
||||
*
|
||||
* @return the API instance.
|
||||
* @return {@link JedisPool}
|
||||
* @throws IllegalStateException if the {@link #getMode()} is not equal to {@link RedisBungeeMode#SINGLE}
|
||||
* @throws IllegalStateException if JedisPool compatibility mode is disabled in the config
|
||||
* @since 0.6.5
|
||||
*/
|
||||
public static RedisBungeeAPI getRedisBungeeApi() {
|
||||
return redisBungeeApi;
|
||||
public JedisPool getJedisPool() {
|
||||
if (getMode() == RedisBungeeMode.SINGLE) {
|
||||
JedisPool jedisPool = ((JedisPooledSummoner) this.plugin.getSummoner()).getCompatibilityJedisPool();
|
||||
if (jedisPool == null) {
|
||||
throw new IllegalStateException("JedisPool compatibility mode is disabled");
|
||||
}
|
||||
return jedisPool;
|
||||
} else {
|
||||
throw new IllegalStateException("Mode is not " + RedisBungeeMode.SINGLE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This gives you an instance of JedisCluster that can't be closed
|
||||
* see {@link com.imaginarycode.minecraft.redisbungee.api.summoners.NotClosableJedisCluster}
|
||||
*
|
||||
* @return {@link redis.clients.jedis.JedisCluster}
|
||||
* @throws IllegalStateException if the {@link #getMode()} is not equal to {@link RedisBungeeMode#CLUSTER}
|
||||
* @since 0.8.0
|
||||
*/
|
||||
public JedisCluster requestClusterJedis() {
|
||||
if (getMode() == RedisBungeeMode.CLUSTER) {
|
||||
return ((JedisClusterSummoner) this.plugin.getSummoner()).obtainResource();
|
||||
} else {
|
||||
throw new IllegalStateException("Mode is not " + RedisBungeeMode.CLUSTER);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This gives you an instance of JedisPooled that can't be closed
|
||||
* see {@link com.imaginarycode.minecraft.redisbungee.api.summoners.NotClosableJedisPooled}
|
||||
*
|
||||
* @return {@link redis.clients.jedis.JedisPooled}
|
||||
* @throws IllegalStateException if the {@link #getMode()} is not equal to {@link RedisBungeeMode#SINGLE}
|
||||
* @since 0.8.0
|
||||
*/
|
||||
public JedisPooled requestJedisPooled() {
|
||||
if (getMode() == RedisBungeeMode.SINGLE) {
|
||||
return ((JedisPooledSummoner) this.plugin.getSummoner()).obtainResource();
|
||||
} else {
|
||||
throw new IllegalStateException("Mode is not " + RedisBungeeMode.SINGLE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* returns Summoner class responsible for Single Jedis {@link redis.clients.jedis.JedisPooled} with {@link JedisPool}, Cluster Jedis {@link redis.clients.jedis.JedisCluster} handling
|
||||
*
|
||||
* @return {@link Summoner}
|
||||
* @since 0.8.0
|
||||
*/
|
||||
public Summoner<?> getSummoner() {
|
||||
return this.plugin.getSummoner();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* shows what mode is RedisBungee is on
|
||||
*
|
||||
* @return {@link RedisBungeeMode}
|
||||
* @since 0.8.0
|
||||
*/
|
||||
public RedisBungeeMode getMode() {
|
||||
return this.plugin.getRedisBungeeMode();
|
||||
}
|
||||
|
||||
public static AbstractRedisBungeeAPI getAbstractRedisBungeeAPI() {
|
||||
return abstractRedisBungeeAPI;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
public class Constants {
|
||||
|
||||
public final static String VERSION = "@version@";
|
||||
public final static String GIT_COMMIT = "@git_commit@";
|
||||
|
||||
public static String getGithubCommitLink() {
|
||||
return "https://github.com/ProxioDev/RedisBungee/commit/" + GIT_COMMIT;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
/**
|
||||
* This used to be old plugin instance of redis-bungee, but now it's used to get the api for old plugins
|
||||
*
|
||||
* @deprecated its deprecated but won't be removed, so please use {@link RedisBungeeAPI#getRedisBungeeApi()}
|
||||
*
|
||||
*/
|
||||
@Deprecated
|
||||
public class RedisBungee {
|
||||
|
||||
private static RedisBungeeAPI api;
|
||||
|
||||
public RedisBungee(RedisBungeeAPI api) {
|
||||
RedisBungee.api = api;
|
||||
}
|
||||
|
||||
/**
|
||||
* This returns an instance of {@link RedisBungeeAPI}
|
||||
*
|
||||
* @deprecated Please use {@link RedisBungeeAPI#getRedisBungeeApi()} this class intended to for old plugins that no longer updated.
|
||||
*
|
||||
* @return the {@link RedisBungeeAPI} object instance.
|
||||
*/
|
||||
@Deprecated
|
||||
public static RedisBungeeAPI getApi() {
|
||||
return api;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -1,4 +1,14 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal;
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api;
|
||||
|
||||
import com.google.common.cache.Cache;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
@@ -8,13 +18,12 @@ import com.google.common.util.concurrent.UncheckedExecutionException;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.tasks.RedisTask;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.net.InetAddress;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@@ -23,15 +32,15 @@ import java.util.concurrent.TimeUnit;
|
||||
*
|
||||
* @since 0.3.3
|
||||
*/
|
||||
public abstract class DataManager<P, PL, PD, PS> {
|
||||
private final RedisBungeePlugin<P> plugin;
|
||||
public abstract class AbstractDataManager<P, PL, PD, PS> {
|
||||
protected final RedisBungeePlugin<P> plugin;
|
||||
private final Cache<UUID, String> serverCache = createCache();
|
||||
private final Cache<UUID, String> proxyCache = createCache();
|
||||
private final Cache<UUID, InetAddress> ipCache = createCache();
|
||||
private final Cache<UUID, Long> lastOnlineCache = createCache();
|
||||
private final Gson gson = new Gson();
|
||||
|
||||
public DataManager(RedisBungeePlugin<P> plugin) {
|
||||
public AbstractDataManager(RedisBungeePlugin<P> plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@@ -43,8 +52,6 @@ public abstract class DataManager<P, PL, PD, PS> {
|
||||
.build();
|
||||
}
|
||||
|
||||
private final JsonParser parser = new JsonParser();
|
||||
|
||||
public String getServer(final UUID uuid) {
|
||||
P player = plugin.getPlayer(uuid);
|
||||
|
||||
@@ -52,12 +59,11 @@ public abstract class DataManager<P, PL, PD, PS> {
|
||||
return plugin.isPlayerOnAServer(player) ? plugin.getPlayerServerName(player) : null;
|
||||
|
||||
try {
|
||||
return serverCache.get(uuid, new Callable<String>() {
|
||||
return serverCache.get(uuid, new RedisTask<String>(plugin) {
|
||||
@Override
|
||||
public String call() throws Exception {
|
||||
try (Jedis tmpRsc = plugin.requestJedis()) {
|
||||
return Objects.requireNonNull(tmpRsc.hget("player:" + uuid, "server"), "user not found");
|
||||
}
|
||||
public String unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
return Objects.requireNonNull(unifiedJedis.hget("player:" + uuid, "server"), "user not found");
|
||||
|
||||
}
|
||||
});
|
||||
} catch (ExecutionException | UncheckedExecutionException e) {
|
||||
@@ -73,15 +79,13 @@ public abstract class DataManager<P, PL, PD, PS> {
|
||||
P player = plugin.getPlayer(uuid);
|
||||
|
||||
if (player != null)
|
||||
return plugin.getConfiguration().getServerId();
|
||||
return plugin.getConfiguration().getProxyId();
|
||||
|
||||
try {
|
||||
return proxyCache.get(uuid, new Callable<String>() {
|
||||
return proxyCache.get(uuid, new RedisTask<String>(plugin) {
|
||||
@Override
|
||||
public String call() throws Exception {
|
||||
try (Jedis tmpRsc = plugin.requestJedis()) {
|
||||
return Objects.requireNonNull(tmpRsc.hget("player:" + uuid, "proxy"), "user not found");
|
||||
}
|
||||
public String unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
return Objects.requireNonNull(unifiedJedis.hget("player:" + uuid, "proxy"), "user not found");
|
||||
}
|
||||
});
|
||||
} catch (ExecutionException | UncheckedExecutionException e) {
|
||||
@@ -99,15 +103,13 @@ public abstract class DataManager<P, PL, PD, PS> {
|
||||
return plugin.getPlayerIp(player);
|
||||
|
||||
try {
|
||||
return ipCache.get(uuid, new Callable<InetAddress>() {
|
||||
return ipCache.get(uuid, new RedisTask<InetAddress>(plugin) {
|
||||
@Override
|
||||
public InetAddress call() throws Exception {
|
||||
try (Jedis tmpRsc = plugin.requestJedis()) {
|
||||
String result = tmpRsc.hget("player:" + uuid, "ip");
|
||||
if (result == null)
|
||||
throw new NullPointerException("user not found");
|
||||
return InetAddresses.forString(result);
|
||||
}
|
||||
public InetAddress unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
String result = unifiedJedis.hget("player:" + uuid, "ip");
|
||||
if (result == null)
|
||||
throw new NullPointerException("user not found");
|
||||
return InetAddresses.forString(result);
|
||||
}
|
||||
});
|
||||
} catch (ExecutionException | UncheckedExecutionException e) {
|
||||
@@ -125,13 +127,12 @@ public abstract class DataManager<P, PL, PD, PS> {
|
||||
return 0;
|
||||
|
||||
try {
|
||||
return lastOnlineCache.get(uuid, new Callable<Long>() {
|
||||
return lastOnlineCache.get(uuid, new RedisTask<Long>(plugin) {
|
||||
|
||||
@Override
|
||||
public Long call() throws Exception {
|
||||
try (Jedis tmpRsc = plugin.requestJedis()) {
|
||||
String result = tmpRsc.hget("player:" + uuid, "online");
|
||||
return result == null ? -1 : Long.valueOf(result);
|
||||
}
|
||||
public Long unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
String result = unifiedJedis.hget("player:" + uuid, "online");
|
||||
return result == null ? -1 : Long.parseLong(result);
|
||||
}
|
||||
});
|
||||
} catch (ExecutionException e) {
|
||||
@@ -149,21 +150,24 @@ public abstract class DataManager<P, PL, PD, PS> {
|
||||
|
||||
// Invalidate all entries related to this player, since they now lie. (call invalidate(uuid))
|
||||
public abstract void onPostLogin(PL event);
|
||||
|
||||
// Invalidate all entries related to this player, since they now lie. (call invalidate(uuid))
|
||||
public abstract void onPlayerDisconnect(PD event);
|
||||
|
||||
public abstract void onPubSubMessage(PS event);
|
||||
|
||||
public abstract boolean handleKick(UUID target, String message);
|
||||
|
||||
protected void handlePubSubMessage(String channel, String message) {
|
||||
if (!channel.equals("redisbungee-data"))
|
||||
return;
|
||||
|
||||
// Partially deserialize the message so we can look at the action
|
||||
JsonObject jsonObject = parser.parse(message).getAsJsonObject();
|
||||
JsonObject jsonObject = JsonParser.parseString(message).getAsJsonObject();
|
||||
|
||||
String source = jsonObject.get("source").getAsString();
|
||||
final String source = jsonObject.get("source").getAsString();
|
||||
|
||||
if (source.equals(plugin.getConfiguration().getServerId()))
|
||||
if (source.equals(plugin.getConfiguration().getProxyId()))
|
||||
return;
|
||||
|
||||
DataManagerMessage.Action action = DataManagerMessage.Action.valueOf(jsonObject.get("action").getAsString());
|
||||
@@ -175,18 +179,9 @@ public abstract class DataManager<P, PL, PD, PS> {
|
||||
proxyCache.put(message1.getTarget(), message1.getSource());
|
||||
lastOnlineCache.put(message1.getTarget(), (long) 0);
|
||||
ipCache.put(message1.getTarget(), message1.getPayload().getAddress());
|
||||
plugin.executeAsync(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Object event;
|
||||
try {
|
||||
event = plugin.getNetworkJoinEventClass().getDeclaredConstructor(UUID.class).newInstance(message1.getTarget());
|
||||
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
|
||||
throw new RuntimeException("unable to dispatch an network join event", e);
|
||||
}
|
||||
plugin.callEvent(event);
|
||||
|
||||
}
|
||||
plugin.executeAsync(() -> {
|
||||
Object event = plugin.createPlayerJoinedNetworkEvent(message1.getTarget());
|
||||
plugin.fireEvent(event);
|
||||
});
|
||||
break;
|
||||
case LEAVE:
|
||||
@@ -194,40 +189,30 @@ public abstract class DataManager<P, PL, PD, PS> {
|
||||
}.getType());
|
||||
invalidate(message2.getTarget());
|
||||
lastOnlineCache.put(message2.getTarget(), message2.getPayload().getTimestamp());
|
||||
plugin.executeAsync(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Object event;
|
||||
try {
|
||||
event = plugin.getNetworkQuitEventClass().getDeclaredConstructor(UUID.class).newInstance(message2.getTarget());
|
||||
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
|
||||
throw new RuntimeException("unable to dispatch an network quit event", e);
|
||||
}
|
||||
plugin.callEvent(event);
|
||||
}
|
||||
plugin.executeAsync(() -> {
|
||||
Object event = plugin.createPlayerLeftNetworkEvent(message2.getTarget());
|
||||
plugin.fireEvent(event);
|
||||
});
|
||||
break;
|
||||
case SERVER_CHANGE:
|
||||
final DataManagerMessage<ServerChangePayload> message3 = gson.fromJson(jsonObject, new TypeToken<DataManagerMessage<ServerChangePayload>>() {
|
||||
}.getType());
|
||||
serverCache.put(message3.getTarget(), message3.getPayload().getServer());
|
||||
plugin.executeAsync(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Object event;
|
||||
try {
|
||||
event = plugin.getServerChangeEventClass().getDeclaredConstructor(UUID.class, String.class, String.class).newInstance(message3.getTarget(), ((ServerChangePayload) message3.getPayload()).getOldServer(), ((ServerChangePayload) message3.getPayload()).getServer());
|
||||
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
|
||||
throw new RuntimeException("unable to dispatch an server change event", e);
|
||||
}
|
||||
plugin.callEvent(event);
|
||||
}
|
||||
plugin.executeAsync(() -> {
|
||||
Object event = plugin.createPlayerChangedServerNetworkEvent(message3.getTarget(), message3.getPayload().getOldServer(), message3.getPayload().getServer());
|
||||
plugin.fireEvent(event);
|
||||
});
|
||||
break;
|
||||
case KICK:
|
||||
final DataManagerMessage<KickPayload> kickPayload = gson.fromJson(jsonObject, new TypeToken<DataManagerMessage<KickPayload>>() {
|
||||
}.getType());
|
||||
plugin.executeAsync(() -> handleKick(kickPayload.target, kickPayload.payload.message));
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public static class DataManagerMessage<T> {
|
||||
public static class DataManagerMessage<T extends Payload> {
|
||||
private final UUID target;
|
||||
private final String source;
|
||||
private final Action action; // for future use!
|
||||
@@ -259,11 +244,28 @@ public abstract class DataManager<P, PL, PD, PS> {
|
||||
public enum Action {
|
||||
JOIN,
|
||||
LEAVE,
|
||||
KICK,
|
||||
SERVER_CHANGE
|
||||
}
|
||||
}
|
||||
|
||||
public static class LoginPayload {
|
||||
public static abstract class Payload {
|
||||
}
|
||||
|
||||
public static class KickPayload extends Payload {
|
||||
|
||||
private final String message;
|
||||
|
||||
public KickPayload(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
public static class LoginPayload extends Payload {
|
||||
private final InetAddress address;
|
||||
|
||||
public LoginPayload(InetAddress address) {
|
||||
@@ -275,7 +277,7 @@ public abstract class DataManager<P, PL, PD, PS> {
|
||||
}
|
||||
}
|
||||
|
||||
public static class ServerChangePayload{
|
||||
public static class ServerChangePayload extends Payload {
|
||||
private final String server;
|
||||
private final String oldServer;
|
||||
|
||||
@@ -294,7 +296,7 @@ public abstract class DataManager<P, PL, PD, PS> {
|
||||
}
|
||||
|
||||
|
||||
public static class LogoutPayload {
|
||||
public static class LogoutPayload extends Payload {
|
||||
private final long timestamp;
|
||||
|
||||
public LogoutPayload(long timestamp) {
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api;
|
||||
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.collect.Multiset;
|
||||
import com.google.common.io.ByteArrayDataOutput;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public abstract class AbstractRedisBungeeListener<LE, PLE, PD, SC, PP, PM, PS> {
|
||||
|
||||
protected final RedisBungeePlugin<?> plugin;
|
||||
protected final List<InetAddress> exemptAddresses;
|
||||
protected final Gson gson = new Gson();
|
||||
|
||||
public AbstractRedisBungeeListener(RedisBungeePlugin<?> plugin, List<InetAddress> exemptAddresses) {
|
||||
this.plugin = plugin;
|
||||
this.exemptAddresses = exemptAddresses;
|
||||
}
|
||||
|
||||
public void onLogin(LE event) {}
|
||||
|
||||
public abstract void onPostLogin(PLE event);
|
||||
|
||||
public abstract void onPlayerDisconnect(PD event);
|
||||
|
||||
public abstract void onServerChange(SC event);
|
||||
|
||||
public abstract void onPing(PP event);
|
||||
|
||||
public abstract void onPluginMessage(PM event);
|
||||
|
||||
public abstract void onPubSubMessage(PS event);
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api;
|
||||
|
||||
|
||||
import redis.clients.jedis.JedisPubSub;
|
||||
|
||||
|
||||
public class JedisPubSubHandler extends JedisPubSub {
|
||||
|
||||
private final RedisBungeePlugin<?> plugin;
|
||||
|
||||
public JedisPubSubHandler(RedisBungeePlugin<?> plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(final String s, final String s2) {
|
||||
if (s2.trim().length() == 0) return;
|
||||
plugin.executeAsync(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Object event = plugin.createPubSubEvent(s, s2);
|
||||
plugin.fireEvent(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,25 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal;
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.tasks.RedisTask;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisCluster;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
import redis.clients.jedis.exceptions.JedisConnectionException;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Level;
|
||||
|
||||
public class PubSubListener implements Runnable {
|
||||
private JedisPubSubHandler jpsh;
|
||||
@@ -21,28 +33,21 @@ public class PubSubListener implements Runnable {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try (Jedis rsc = plugin.requestJedis()) {
|
||||
try {
|
||||
|
||||
RedisTask<Void> subTask = new RedisTask<Void>(plugin) {
|
||||
@Override
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
jpsh = new JedisPubSubHandler(plugin);
|
||||
addedChannels.add("redisbungee-" + plugin.getConfiguration().getServerId());
|
||||
addedChannels.add("redisbungee-" + plugin.getConfiguration().getProxyId());
|
||||
addedChannels.add("redisbungee-allservers");
|
||||
addedChannels.add("redisbungee-data");
|
||||
rsc.subscribe(jpsh, addedChannels.toArray(new String[0]));
|
||||
} catch (Exception e) {
|
||||
// FIXME: Extremely ugly hack
|
||||
// Attempt to unsubscribe this instance and try again.
|
||||
plugin.logWarn("PubSub error, attempting to recover.");
|
||||
try {
|
||||
jpsh.unsubscribe();
|
||||
} catch (Exception e1) {
|
||||
/* This may fail with
|
||||
- java.net.SocketException: Broken pipe
|
||||
- redis.clients.jedis.exceptions.JedisConnectionException: JedisPubSub was not subscribed to a Jedis instance
|
||||
*/
|
||||
}
|
||||
unifiedJedis.subscribe(jpsh, addedChannels.toArray(new String[0]));
|
||||
return null;
|
||||
}
|
||||
} catch (JedisConnectionException e) {
|
||||
};
|
||||
|
||||
try {
|
||||
subTask.execute();
|
||||
} catch (Exception e) {
|
||||
plugin.logWarn("PubSub error, attempting to recover in 5 secs.");
|
||||
plugin.executeAsyncAfter(this, TimeUnit.SECONDS, 5);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api;
|
||||
|
||||
public enum RedisBungeeMode {
|
||||
SINGLE, CLUSTER
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMultimap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.imaginarycode.minecraft.redisbungee.AbstractRedisBungeeAPI;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.config.RedisBungeeConfiguration;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.EventsPlatform;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.summoners.Summoner;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.tasks.RedisTask;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.RedisUtil;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.payload.PayloadUtils;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.uuid.UUIDTranslator;
|
||||
import redis.clients.jedis.Protocol;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
import redis.clients.jedis.exceptions.JedisConnectionException;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
|
||||
|
||||
/**
|
||||
* This Class has all internal methods needed by every redis bungee plugin, and it can be used to implement another platforms than bungeecord or another forks of RedisBungee
|
||||
* <p>
|
||||
* Reason this is interface because some proxies implementations require the user to extend class for plugins for example bungeecord.
|
||||
*
|
||||
* @author Ham1255
|
||||
* @since 0.7.0
|
||||
*/
|
||||
public interface RedisBungeePlugin<P> extends EventsPlatform {
|
||||
|
||||
default void initialize() {
|
||||
|
||||
}
|
||||
|
||||
default void stop() {
|
||||
|
||||
}
|
||||
|
||||
Summoner<?> getSummoner();
|
||||
|
||||
RedisBungeeConfiguration getConfiguration();
|
||||
|
||||
int getCount();
|
||||
|
||||
default int getCurrentCount() {
|
||||
return new RedisTask<Long>(this) {
|
||||
@Override
|
||||
public Long unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
long total = 0;
|
||||
long redisTime = getRedisTime(unifiedJedis);
|
||||
Map<String, String> heartBeats = unifiedJedis.hgetAll("heartbeats");
|
||||
for (Map.Entry<String, String> stringStringEntry : heartBeats.entrySet()) {
|
||||
String k = stringStringEntry.getKey();
|
||||
String v = stringStringEntry.getValue();
|
||||
|
||||
long heartbeatTime = Long.parseLong(v);
|
||||
if (heartbeatTime + RedisUtil.PROXY_TIMEOUT >= redisTime) {
|
||||
total = total + unifiedJedis.scard("proxy:" + k + ":usersOnline");
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
}.execute().intValue();
|
||||
}
|
||||
|
||||
Set<String> getLocalPlayersAsUuidStrings();
|
||||
|
||||
AbstractDataManager<P, ?, ?, ?> getDataManager();
|
||||
|
||||
default Set<UUID> getPlayers() {
|
||||
return new RedisTask<Set<UUID>>(this) {
|
||||
@Override
|
||||
public Set<UUID> unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
ImmutableSet.Builder<UUID> setBuilder = ImmutableSet.builder();
|
||||
try {
|
||||
List<String> keys = new ArrayList<>();
|
||||
for (String i : getProxiesIds()) {
|
||||
keys.add("proxy:" + i + ":usersOnline");
|
||||
}
|
||||
if (!keys.isEmpty()) {
|
||||
Set<String> users = unifiedJedis.sunion(keys.toArray(new String[0]));
|
||||
if (users != null && !users.isEmpty()) {
|
||||
for (String user : users) {
|
||||
try {
|
||||
setBuilder = setBuilder.add(UUID.fromString(user));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (JedisConnectionException e) {
|
||||
// Redis server has disappeared!
|
||||
logFatal("Unable to get connection from pool - did your Redis server go away?");
|
||||
throw new RuntimeException("Unable to get all players online", e);
|
||||
}
|
||||
return setBuilder.build();
|
||||
}
|
||||
}.execute();
|
||||
}
|
||||
|
||||
AbstractRedisBungeeAPI getAbstractRedisBungeeApi();
|
||||
|
||||
UUIDTranslator getUuidTranslator();
|
||||
|
||||
Multimap<String, UUID> serverToPlayersCache();
|
||||
|
||||
default Multimap<String, UUID> serversToPlayers() {
|
||||
return new RedisTask<Multimap<String, UUID>>(this) {
|
||||
@Override
|
||||
public Multimap<String, UUID> unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
ImmutableMultimap.Builder<String, UUID> builder = ImmutableMultimap.builder();
|
||||
for (String serverId : getProxiesIds()) {
|
||||
Set<String> players = unifiedJedis.smembers("proxy:" + serverId + ":usersOnline");
|
||||
for (String player : players) {
|
||||
String playerServer = unifiedJedis.hget("player:" + player, "server");
|
||||
if (playerServer == null) {
|
||||
continue;
|
||||
}
|
||||
builder.put(playerServer, UUID.fromString(player));
|
||||
}
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
}.execute();
|
||||
}
|
||||
|
||||
default Set<UUID> getPlayersOnProxy(String proxyId) {
|
||||
checkArgument(getProxiesIds().contains(proxyId), proxyId + " is not a valid proxy ID");
|
||||
return new RedisTask<Set<UUID>>(this) {
|
||||
@Override
|
||||
public Set<UUID> unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
Set<String> users = unifiedJedis.smembers("proxy:" + proxyId + ":usersOnline");
|
||||
ImmutableSet.Builder<UUID> builder = ImmutableSet.builder();
|
||||
for (String user : users) {
|
||||
builder.add(UUID.fromString(user));
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
}.execute();
|
||||
}
|
||||
|
||||
default void sendProxyCommand(String proxyId, String command) {
|
||||
checkArgument(getProxiesIds().contains(proxyId) || proxyId.equals("allservers"), "proxyId is invalid");
|
||||
sendChannelMessage("redisbungee-" + proxyId, command);
|
||||
}
|
||||
|
||||
List<String> getProxiesIds();
|
||||
|
||||
default List<String> getCurrentProxiesIds(boolean lagged) {
|
||||
return new RedisTask<List<String>>(this) {
|
||||
@Override
|
||||
public List<String> unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
try {
|
||||
long time = getRedisTime(unifiedJedis);
|
||||
ImmutableList.Builder<String> servers = ImmutableList.builder();
|
||||
Map<String, String> heartbeats = unifiedJedis.hgetAll("heartbeats");
|
||||
for (Map.Entry<String, String> entry : heartbeats.entrySet()) {
|
||||
try {
|
||||
long stamp = Long.parseLong(entry.getValue());
|
||||
if (lagged ? time >= stamp + RedisUtil.PROXY_TIMEOUT : time <= stamp + RedisUtil.PROXY_TIMEOUT) {
|
||||
servers.add(entry.getKey());
|
||||
} else if (time > stamp + RedisUtil.PROXY_TIMEOUT) {
|
||||
logWarn(entry.getKey() + " is " + (time - stamp) + " seconds behind! (Time not synchronized or server down?) and was removed from heartbeat.");
|
||||
unifiedJedis.hdel("heartbeats", entry.getKey());
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
return servers.build();
|
||||
} catch (JedisConnectionException e) {
|
||||
logFatal("Unable to fetch server IDs");
|
||||
e.printStackTrace();
|
||||
return Collections.singletonList(getConfiguration().getProxyId());
|
||||
}
|
||||
}
|
||||
}.execute();
|
||||
}
|
||||
|
||||
PubSubListener getPubSubListener();
|
||||
|
||||
default void sendChannelMessage(String channel, String message) {
|
||||
new RedisTask<Void>(this) {
|
||||
@Override
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
try {
|
||||
unifiedJedis.publish(channel, message);
|
||||
} catch (JedisConnectionException e) {
|
||||
// Redis server has disappeared!
|
||||
logFatal("Unable to get connection from pool - did your Redis server go away?");
|
||||
throw new RuntimeException("Unable to publish channel message", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}.execute();
|
||||
}
|
||||
|
||||
void executeAsync(Runnable runnable);
|
||||
|
||||
void executeAsyncAfter(Runnable runnable, TimeUnit timeUnit, int time);
|
||||
|
||||
boolean isOnlineMode();
|
||||
|
||||
void logInfo(String msg);
|
||||
|
||||
void logWarn(String msg);
|
||||
|
||||
void logFatal(String msg);
|
||||
|
||||
P getPlayer(UUID uuid);
|
||||
|
||||
P getPlayer(String name);
|
||||
|
||||
UUID getPlayerUUID(String player);
|
||||
|
||||
String getPlayerName(UUID player);
|
||||
|
||||
String getPlayerServerName(P player);
|
||||
|
||||
boolean isPlayerOnAServer(P player);
|
||||
|
||||
InetAddress getPlayerIp(P player);
|
||||
|
||||
default void sendProxyCommand(String cmd) {
|
||||
sendProxyCommand(getConfiguration().getProxyId(), cmd);
|
||||
}
|
||||
|
||||
default Long getRedisTime(UnifiedJedis unifiedJedis) {
|
||||
List<Object> data = (List<Object>) unifiedJedis.sendCommand(Protocol.Command.TIME);
|
||||
List<String> times = new ArrayList<>();
|
||||
data.forEach((o) -> times.add(new String((byte[])o)));
|
||||
return getRedisTime(times);
|
||||
}
|
||||
default long getRedisTime(List<String> timeRes) {
|
||||
return Long.parseLong(timeRes.get(0));
|
||||
}
|
||||
|
||||
default void kickPlayer(UUID playerUniqueId, String message) {
|
||||
// first handle on origin proxy if player not found publish the payload
|
||||
if (!getDataManager().handleKick(playerUniqueId, message)) {
|
||||
new RedisTask<Void>(this) {
|
||||
@Override
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
PayloadUtils.kickPlayerPayload(playerUniqueId, message, unifiedJedis);
|
||||
return null;
|
||||
}
|
||||
}.execute();
|
||||
}
|
||||
}
|
||||
|
||||
default void kickPlayer(String playerName, String message) {
|
||||
// fetch the uuid from name
|
||||
UUID playerUUID = getUuidTranslator().getTranslatedUuid(playerName, true);
|
||||
kickPlayer(playerUUID, message);
|
||||
}
|
||||
|
||||
RedisBungeeMode getRedisBungeeMode();
|
||||
|
||||
void updateProxiesIds();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.config;
|
||||
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.reflect.TypeToken;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeeMode;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.summoners.JedisClusterSummoner;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.summoners.JedisPooledSummoner;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.summoners.Summoner;
|
||||
import ninja.leaping.configurate.ConfigurationNode;
|
||||
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
|
||||
import ninja.leaping.configurate.yaml.YAMLConfigurationLoader;
|
||||
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
|
||||
import redis.clients.jedis.*;
|
||||
import redis.clients.jedis.providers.ClusterConnectionProvider;
|
||||
import redis.clients.jedis.providers.PooledConnectionProvider;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.*;
|
||||
|
||||
public interface ConfigLoader {
|
||||
|
||||
default void loadConfig(RedisBungeePlugin<?> plugin, File dataFolder) throws IOException {
|
||||
loadConfig(plugin, dataFolder.toPath());
|
||||
}
|
||||
|
||||
default void loadConfig(RedisBungeePlugin<?> plugin, Path dataFolder) throws IOException {
|
||||
Path configFile = createConfigFile(dataFolder);
|
||||
final YAMLConfigurationLoader yamlConfigurationFileLoader = YAMLConfigurationLoader.builder().setPath(configFile).build();
|
||||
ConfigurationNode node = yamlConfigurationFileLoader.load();
|
||||
if (node.getNode("config-version").getInt(0) != RedisBungeeConfiguration.CONFIG_VERSION) {
|
||||
handleOldConfig(dataFolder);
|
||||
node = yamlConfigurationFileLoader.load();
|
||||
}
|
||||
final boolean useSSL = node.getNode("useSSL").getBoolean(false);
|
||||
final boolean overrideBungeeCommands = node.getNode("override-bungee-commands").getBoolean(false);
|
||||
final boolean registerLegacyCommands = node.getNode("register-legacy-commands").getBoolean(false);
|
||||
final boolean restoreOldKickBehavior = node.getNode("disable-kick-when-online").getBoolean(false);
|
||||
String redisPassword = node.getNode("redis-password").getString("");
|
||||
String redisUsername = node.getNode("redis-username").getString("");
|
||||
String proxyId = node.getNode("proxy-id").getString("test-1");
|
||||
final int maxConnections = node.getNode("max-redis-connections").getInt(10);
|
||||
List<String> exemptAddresses;
|
||||
try {
|
||||
exemptAddresses = node.getNode("exempt-ip-addresses").getList(TypeToken.of(String.class));
|
||||
} catch (ObjectMappingException e) {
|
||||
exemptAddresses = Collections.emptyList();
|
||||
}
|
||||
|
||||
// check redis password
|
||||
if ((redisPassword.isEmpty() || redisPassword.equals("none"))) {
|
||||
redisPassword = null;
|
||||
plugin.logWarn("password is empty");
|
||||
}
|
||||
if ((redisUsername.isEmpty() || redisUsername.equals("none"))) {
|
||||
redisUsername = null;
|
||||
}
|
||||
|
||||
if (useSSL) {
|
||||
plugin.logInfo("Using ssl");
|
||||
}
|
||||
// Configuration sanity checks.
|
||||
if (proxyId == null || proxyId.isEmpty()) {
|
||||
String genId = UUID.randomUUID().toString();
|
||||
plugin.logInfo("Generated proxy id " + genId + " and saving it to config.");
|
||||
node.getNode("proxy-id").setValue(genId);
|
||||
yamlConfigurationFileLoader.save(node);
|
||||
proxyId = genId;
|
||||
plugin.logInfo("proxy id was generated: " + proxyId);
|
||||
} else {
|
||||
plugin.logInfo("Loaded proxy id " + proxyId);
|
||||
}
|
||||
RedisBungeeConfiguration configuration = new RedisBungeeConfiguration(proxyId, exemptAddresses, registerLegacyCommands, overrideBungeeCommands, getMessagesFromPath(createMessagesFile(dataFolder)), restoreOldKickBehavior);
|
||||
Summoner<?> summoner;
|
||||
RedisBungeeMode redisBungeeMode;
|
||||
if (node.getNode("cluster-mode-enabled").getBoolean(false)) {
|
||||
plugin.logInfo("RedisBungee MODE: CLUSTER");
|
||||
Set<HostAndPort> hostAndPortSet = new HashSet<>();
|
||||
GenericObjectPoolConfig<Connection> poolConfig = new GenericObjectPoolConfig<>();
|
||||
poolConfig.setMaxTotal(maxConnections);
|
||||
poolConfig.setBlockWhenExhausted(true);
|
||||
node.getNode("redis-cluster-servers").getChildrenList().forEach((childNode) -> {
|
||||
Map<Object, ? extends ConfigurationNode> hostAndPort = childNode.getChildrenMap();
|
||||
String host = hostAndPort.get("host").getString();
|
||||
int port = hostAndPort.get("port").getInt();
|
||||
hostAndPortSet.add(new HostAndPort(host, port));
|
||||
});
|
||||
plugin.logInfo(hostAndPortSet.size() + " cluster nodes were specified");
|
||||
if (hostAndPortSet.isEmpty()) {
|
||||
throw new RuntimeException("No redis cluster servers specified");
|
||||
}
|
||||
summoner = new JedisClusterSummoner(new ClusterConnectionProvider(hostAndPortSet, DefaultJedisClientConfig.builder().user(redisUsername).password(redisPassword).ssl(useSSL).socketTimeoutMillis(5000).timeoutMillis(10000).build(), poolConfig));
|
||||
redisBungeeMode = RedisBungeeMode.CLUSTER;
|
||||
} else {
|
||||
plugin.logInfo("RedisBungee MODE: SINGLE");
|
||||
final String redisServer = node.getNode("redis-server").getString("127.0.0.1");
|
||||
final int redisPort = node.getNode("redis-port").getInt(6379);
|
||||
if (redisServer != null && redisServer.isEmpty()) {
|
||||
throw new RuntimeException("No redis server specified");
|
||||
}
|
||||
JedisPool jedisPool = null;
|
||||
if (node.getNode("enable-jedis-pool-compatibility").getBoolean(true)) {
|
||||
JedisPoolConfig config = new JedisPoolConfig();
|
||||
config.setMaxTotal(node.getNode("compatibility-max-connections").getInt(3));
|
||||
config.setBlockWhenExhausted(true);
|
||||
jedisPool = new JedisPool(config, redisServer, redisPort, 5000, redisUsername, redisPassword, useSSL);
|
||||
plugin.logInfo("Compatibility JedisPool was created");
|
||||
}
|
||||
GenericObjectPoolConfig<Connection> poolConfig = new GenericObjectPoolConfig<>();
|
||||
poolConfig.setMaxTotal(maxConnections);
|
||||
poolConfig.setBlockWhenExhausted(true);
|
||||
summoner = new JedisPooledSummoner(new PooledConnectionProvider(new ConnectionFactory(new HostAndPort(redisServer, redisPort), DefaultJedisClientConfig.builder().user(redisUsername).timeoutMillis(5000).ssl(useSSL).password(redisPassword).build()), poolConfig), jedisPool);
|
||||
redisBungeeMode = RedisBungeeMode.SINGLE;
|
||||
}
|
||||
plugin.logInfo("Successfully connected to Redis.");
|
||||
onConfigLoad(configuration, summoner, redisBungeeMode);
|
||||
}
|
||||
|
||||
void onConfigLoad(RedisBungeeConfiguration configuration, Summoner<?> summoner, RedisBungeeMode mode);
|
||||
|
||||
default ImmutableMap<RedisBungeeConfiguration.MessageType, String> getMessagesFromPath(Path path) throws IOException {
|
||||
final YAMLConfigurationLoader yamlConfigurationFileLoader = YAMLConfigurationLoader.builder().setPath(path).build();
|
||||
ConfigurationNode node = yamlConfigurationFileLoader.load();
|
||||
HashMap<RedisBungeeConfiguration.MessageType, String> messages = new HashMap<>();
|
||||
messages.put(RedisBungeeConfiguration.MessageType.LOGGED_IN_OTHER_LOCATION, node.getNode("logged-in-other-location").getString("§cLogged in from another location."));
|
||||
messages.put(RedisBungeeConfiguration.MessageType.ALREADY_LOGGED_IN, node.getNode("already-logged-in").getString("§cYou are already logged in!"));
|
||||
return ImmutableMap.copyOf(messages);
|
||||
}
|
||||
|
||||
default Path createMessagesFile(Path dataFolder) throws IOException {
|
||||
if (Files.notExists(dataFolder)) {
|
||||
Files.createDirectory(dataFolder);
|
||||
}
|
||||
Path file = dataFolder.resolve("messages.yml");
|
||||
if (Files.notExists(file)) {
|
||||
try (InputStream in = getClass().getClassLoader().getResourceAsStream("messages.yml")) {
|
||||
Files.createFile(file);
|
||||
assert in != null;
|
||||
Files.copy(in, file, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
default Path createConfigFile(Path dataFolder) throws IOException {
|
||||
if (Files.notExists(dataFolder)) {
|
||||
Files.createDirectory(dataFolder);
|
||||
}
|
||||
Path file = dataFolder.resolve("config.yml");
|
||||
if (Files.notExists(file)) {
|
||||
try (InputStream in = getClass().getClassLoader().getResourceAsStream("config.yml")) {
|
||||
Files.createFile(file);
|
||||
assert in != null;
|
||||
Files.copy(in, file, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
default void handleOldConfig(Path dataFolder) throws IOException {
|
||||
Path oldConfigFolder = dataFolder.resolve("old_config");
|
||||
if (Files.notExists(oldConfigFolder)) {
|
||||
Files.createDirectory(oldConfigFolder);
|
||||
}
|
||||
Path oldConfigPath = dataFolder.resolve("config.yml");
|
||||
Files.move(oldConfigPath, oldConfigFolder.resolve(UUID.randomUUID() + "_config.yml"));
|
||||
createConfigFile(dataFolder);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.config;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableMultimap;
|
||||
import com.google.common.net.InetAddresses;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
public class RedisBungeeConfiguration {
|
||||
|
||||
public enum MessageType {
|
||||
LOGGED_IN_OTHER_LOCATION,
|
||||
ALREADY_LOGGED_IN
|
||||
}
|
||||
|
||||
private final ImmutableMap<MessageType, String> messages;
|
||||
public static final int CONFIG_VERSION = 1;
|
||||
private final String proxyId;
|
||||
private final List<InetAddress> exemptAddresses;
|
||||
private final boolean registerLegacyCommands;
|
||||
private final boolean overrideBungeeCommands;
|
||||
|
||||
private final boolean restoreOldKickBehavior;
|
||||
|
||||
public RedisBungeeConfiguration(String proxyId, List<String> exemptAddresses, boolean registerLegacyCommands, boolean overrideBungeeCommands, ImmutableMap<MessageType, String> messages, boolean restoreOldKickBehavior) {
|
||||
this.proxyId = proxyId;
|
||||
this.messages = messages;
|
||||
ImmutableList.Builder<InetAddress> addressBuilder = ImmutableList.builder();
|
||||
for (String s : exemptAddresses) {
|
||||
addressBuilder.add(InetAddresses.forString(s));
|
||||
}
|
||||
this.exemptAddresses = addressBuilder.build();
|
||||
this.registerLegacyCommands = registerLegacyCommands;
|
||||
this.overrideBungeeCommands = overrideBungeeCommands;
|
||||
this.restoreOldKickBehavior = restoreOldKickBehavior;
|
||||
}
|
||||
public String getProxyId() {
|
||||
return proxyId;
|
||||
}
|
||||
|
||||
public List<InetAddress> getExemptAddresses() {
|
||||
return exemptAddresses;
|
||||
}
|
||||
|
||||
public boolean doRegisterLegacyCommands() {
|
||||
return registerLegacyCommands;
|
||||
}
|
||||
|
||||
public boolean doOverrideBungeeCommands() {
|
||||
return overrideBungeeCommands;
|
||||
}
|
||||
|
||||
public ImmutableMap<MessageType, String> getMessages() {
|
||||
return messages;
|
||||
}
|
||||
|
||||
public boolean restoreOldKickBehavior() {
|
||||
return restoreOldKickBehavior;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.events;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Since each platform have their own events' implementation for example Bungeecord events extends Event while velocity don't
|
||||
*
|
||||
* @author Ham1255
|
||||
* @since 0.7.0
|
||||
*
|
||||
*/
|
||||
public interface EventsPlatform {
|
||||
|
||||
IPlayerChangedServerNetworkEvent createPlayerChangedServerNetworkEvent(UUID uuid, String previousServer, String server);
|
||||
|
||||
IPlayerJoinedNetworkEvent createPlayerJoinedNetworkEvent(UUID uuid);
|
||||
|
||||
IPlayerLeftNetworkEvent createPlayerLeftNetworkEvent(UUID uuid);
|
||||
|
||||
IPubSubMessageEvent createPubSubEvent(String channel, String message);
|
||||
|
||||
void fireEvent(Object event);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.events;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface IPlayerChangedServerNetworkEvent extends RedisBungeeEvent {
|
||||
|
||||
UUID getUuid();
|
||||
|
||||
String getServer();
|
||||
|
||||
String getPreviousServer();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.events;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface IPlayerJoinedNetworkEvent extends RedisBungeeEvent {
|
||||
|
||||
UUID getUuid();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.events;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface IPlayerLeftNetworkEvent extends RedisBungeeEvent {
|
||||
|
||||
UUID getUuid();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.events;
|
||||
|
||||
public interface IPubSubMessageEvent extends RedisBungeeEvent {
|
||||
|
||||
String getChannel();
|
||||
|
||||
String getMessage();
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.events;
|
||||
|
||||
interface RedisBungeeEvent {
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.summoners;
|
||||
|
||||
import redis.clients.jedis.JedisCluster;
|
||||
import redis.clients.jedis.providers.ClusterConnectionProvider;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
|
||||
public class JedisClusterSummoner implements Summoner<JedisCluster> {
|
||||
public final ClusterConnectionProvider clusterConnectionProvider;
|
||||
|
||||
public JedisClusterSummoner(ClusterConnectionProvider clusterConnectionProvider) {
|
||||
this.clusterConnectionProvider = clusterConnectionProvider;
|
||||
// test the connection
|
||||
JedisCluster jedisCluster = obtainResource();
|
||||
jedisCluster.set("random_data", "0");
|
||||
jedisCluster.del("random_data");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
this.clusterConnectionProvider.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public JedisCluster obtainResource() {
|
||||
return new NotClosableJedisCluster(this.clusterConnectionProvider, 60, Duration.ofSeconds(30000));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.summoners;
|
||||
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.JedisPooled;
|
||||
import redis.clients.jedis.providers.PooledConnectionProvider;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class JedisPooledSummoner implements Summoner<JedisPooled> {
|
||||
|
||||
private final PooledConnectionProvider connectionProvider;
|
||||
private final JedisPool jedisPool;
|
||||
|
||||
public JedisPooledSummoner(PooledConnectionProvider connectionProvider, JedisPool jedisPool) {
|
||||
this.connectionProvider = connectionProvider;
|
||||
this.jedisPool = jedisPool;
|
||||
// test connections
|
||||
if (jedisPool != null) {
|
||||
try (Jedis jedis = this.jedisPool.getResource()) {
|
||||
// Test the connection to make sure configuration is right
|
||||
jedis.ping();
|
||||
}
|
||||
|
||||
}
|
||||
final JedisPooled jedisPooled = this.obtainResource();
|
||||
jedisPooled.set("random_data", "0");
|
||||
jedisPooled.del("random_data");
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public JedisPooled obtainResource() {
|
||||
// create UnClosable JedisPool *disposable*
|
||||
return new NotClosableJedisPooled(this.connectionProvider);
|
||||
}
|
||||
|
||||
public JedisPool getCompatibilityJedisPool() {
|
||||
return this.jedisPool;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
if (this.jedisPool != null) {
|
||||
this.jedisPool.close();
|
||||
}
|
||||
this.connectionProvider.close();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.summoners;
|
||||
|
||||
import redis.clients.jedis.JedisCluster;
|
||||
import redis.clients.jedis.JedisPooled;
|
||||
import redis.clients.jedis.providers.ClusterConnectionProvider;
|
||||
import redis.clients.jedis.providers.PooledConnectionProvider;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
|
||||
public class NotClosableJedisCluster extends JedisCluster {
|
||||
|
||||
NotClosableJedisCluster(ClusterConnectionProvider provider, int maxAttempts, Duration maxTotalRetriesDuration) {
|
||||
super(provider, maxAttempts, maxTotalRetriesDuration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.summoners;
|
||||
|
||||
import redis.clients.jedis.JedisPooled;
|
||||
import redis.clients.jedis.providers.PooledConnectionProvider;
|
||||
|
||||
|
||||
public class NotClosableJedisPooled extends JedisPooled {
|
||||
NotClosableJedisPooled(PooledConnectionProvider provider) {
|
||||
super(provider);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.summoners;
|
||||
|
||||
import java.io.Closeable;
|
||||
|
||||
|
||||
/**
|
||||
* This class intended for future release to support redis sentinel or redis clusters
|
||||
*
|
||||
* @author Ham1255
|
||||
* @since 0.7.0
|
||||
*
|
||||
*/
|
||||
public interface Summoner<P> extends Closeable {
|
||||
|
||||
P obtainResource();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.tasks;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisCluster;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
import redis.clients.jedis.exceptions.JedisConnectionException;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class HeartbeatTask extends RedisTask<Void>{
|
||||
|
||||
public final static TimeUnit REPEAT_INTERVAL_TIME_UNIT = TimeUnit.SECONDS;
|
||||
public final static int INTERVAL = 1;
|
||||
private final AtomicInteger globalPlayerCount;
|
||||
|
||||
public HeartbeatTask(RedisBungeePlugin<?> plugin, AtomicInteger globalPlayerCount) {
|
||||
super(plugin);
|
||||
this.globalPlayerCount = globalPlayerCount;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
try {
|
||||
long redisTime = plugin.getRedisTime(unifiedJedis);
|
||||
unifiedJedis.hset("heartbeats", plugin.getConfiguration().getProxyId(), String.valueOf(redisTime));
|
||||
} catch (JedisConnectionException e) {
|
||||
// Redis server has disappeared!
|
||||
plugin.logFatal("Unable to update heartbeat - did your Redis server go away?");
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
plugin.updateProxiesIds();
|
||||
globalPlayerCount.set(plugin.getCurrentCount());
|
||||
} catch (Throwable e) {
|
||||
plugin.logFatal("Unable to update data - did your Redis server go away?");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.tasks;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.RedisUtil;
|
||||
import redis.clients.jedis.Protocol;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class InitialUtils {
|
||||
|
||||
public static void checkRedisVersion(RedisBungeePlugin<?> plugin) {
|
||||
new RedisTask<Void>(plugin) {
|
||||
@Override
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
// This is more portable than INFO <section>
|
||||
String info = new String((byte[]) unifiedJedis.sendCommand(Protocol.Command.INFO));
|
||||
for (String s : info.split("\r\n")) {
|
||||
if (s.startsWith("redis_version:")) {
|
||||
String version = s.split(":")[1];
|
||||
plugin.logInfo("Redis server version: " + version);
|
||||
if (!RedisUtil.isRedisVersionRight(version)) {
|
||||
plugin.logFatal("Your version of Redis (" + version + ") is not at least version 3.0 RedisBungee requires a newer version of Redis.");
|
||||
throw new RuntimeException("Unsupported Redis version detected");
|
||||
}
|
||||
long uuidCacheSize = unifiedJedis.hlen("uuid-cache");
|
||||
if (uuidCacheSize > 750000) {
|
||||
plugin.logInfo("Looks like you have a really big UUID cache! Run https://github.com/ProxioDev/Brains");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}.execute();
|
||||
}
|
||||
|
||||
|
||||
public static void checkIfRecovering(RedisBungeePlugin<?> plugin, Path dataFolder) {
|
||||
new RedisTask<Void>(plugin) {
|
||||
@Override
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
Path crashFile = dataFolder.resolve("restarted_from_crash.txt");
|
||||
if (Files.exists(crashFile)) {
|
||||
try {
|
||||
Files.delete(crashFile);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
plugin.logInfo("crash file was deleted continuing RedisBungee startup ");
|
||||
} else if (unifiedJedis.hexists("heartbeats", plugin.getConfiguration().getProxyId())) {
|
||||
try {
|
||||
long value = Long.parseLong(unifiedJedis.hget("heartbeats", plugin.getConfiguration().getProxyId()));
|
||||
long redisTime = plugin.getRedisTime(unifiedJedis);
|
||||
|
||||
if (redisTime < value + RedisUtil.PROXY_TIMEOUT) {
|
||||
logImposter(plugin);
|
||||
throw new RuntimeException("Possible impostor instance!");
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}.execute();
|
||||
}
|
||||
|
||||
private static void logImposter(RedisBungeePlugin<?> plugin) {
|
||||
plugin.logFatal("You have launched a possible impostor Velocity / Bungeecord instance. Another instance is already running.");
|
||||
plugin.logFatal("For data consistency reasons, RedisBungee will now disable itself.");
|
||||
plugin.logFatal("If this instance is coming up from a crash, create a file in your RedisBungee plugins directory with the name 'restarted_from_crash.txt' and RedisBungee will not perform this check.");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.tasks;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.player.PlayerUtils;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public abstract class IntegrityCheckTask extends RedisTask<Void> {
|
||||
|
||||
public static int INTERVAL = 30;
|
||||
public static TimeUnit TIMEUNIT = TimeUnit.SECONDS;
|
||||
|
||||
|
||||
public IntegrityCheckTask(RedisBungeePlugin<?> plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
try {
|
||||
Set<String> players = plugin.getLocalPlayersAsUuidStrings();
|
||||
Set<String> playersInRedis = unifiedJedis.smembers("proxy:" + plugin.getConfiguration().getProxyId() + ":usersOnline");
|
||||
List<String> lagged = plugin.getCurrentProxiesIds(true);
|
||||
|
||||
// Clean up lagged players.
|
||||
for (String s : lagged) {
|
||||
Set<String> laggedPlayers = unifiedJedis.smembers("proxy:" + s + ":usersOnline");
|
||||
unifiedJedis.del("proxy:" + s + ":usersOnline");
|
||||
if (!laggedPlayers.isEmpty()) {
|
||||
plugin.logInfo("Cleaning up lagged proxy " + s + " (" + laggedPlayers.size() + " players)...");
|
||||
for (String laggedPlayer : laggedPlayers) {
|
||||
PlayerUtils.cleanUpPlayer(laggedPlayer, unifiedJedis, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> absentLocally = new HashSet<>(playersInRedis);
|
||||
absentLocally.removeAll(players);
|
||||
Set<String> absentInRedis = new HashSet<>(players);
|
||||
absentInRedis.removeAll(playersInRedis);
|
||||
|
||||
for (String member : absentLocally) {
|
||||
boolean found = false;
|
||||
for (String proxyId : plugin.getProxiesIds()) {
|
||||
if (proxyId.equals(plugin.getConfiguration().getProxyId())) continue;
|
||||
if (unifiedJedis.sismember("proxy:" + proxyId + ":usersOnline", member)) {
|
||||
// Just clean up the set.
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
PlayerUtils.cleanUpPlayer(member, unifiedJedis, false);
|
||||
plugin.logWarn("Player found in set that was not found locally and globally: " + member);
|
||||
} else {
|
||||
unifiedJedis.srem("proxy:" + plugin.getConfiguration().getProxyId() + ":usersOnline", member);
|
||||
plugin.logWarn("Player found in set that was not found locally, but is on another proxy: " + member);
|
||||
}
|
||||
}
|
||||
// due unifiedJedis does not support pipelined.
|
||||
//Pipeline pipeline = jedis.pipelined();
|
||||
|
||||
for (String player : absentInRedis) {
|
||||
// Player not online according to Redis but not BungeeCord.
|
||||
handlePlatformPlayer(player, unifiedJedis);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
plugin.logFatal("Unable to fix up stored player data");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public abstract void handlePlatformPlayer(String player, UnifiedJedis unifiedJedis);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.tasks;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.AbstractRedisBungeeAPI;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.summoners.JedisClusterSummoner;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.summoners.JedisPooledSummoner;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.summoners.Summoner;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeeMode;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
/**
|
||||
* Since Jedis now have UnifiedJedis which basically extended by cluster / single connections classes
|
||||
* can help us to have shared code.
|
||||
*/
|
||||
public abstract class RedisTask<V> implements Runnable, Callable<V> {
|
||||
|
||||
protected final Summoner<?> summoner;
|
||||
protected final AbstractRedisBungeeAPI api;
|
||||
protected RedisBungeePlugin<?> plugin;
|
||||
|
||||
@Override
|
||||
public V call() throws Exception {
|
||||
return execute();
|
||||
}
|
||||
|
||||
public RedisTask(AbstractRedisBungeeAPI api) {
|
||||
this.api = api;
|
||||
this.summoner = api.getSummoner();
|
||||
}
|
||||
|
||||
public RedisTask(RedisBungeePlugin<?> plugin) {
|
||||
this.plugin = plugin;
|
||||
this.api = plugin.getAbstractRedisBungeeApi();
|
||||
this.summoner = api.getSummoner();
|
||||
}
|
||||
|
||||
public abstract V unifiedJedisTask(UnifiedJedis unifiedJedis);
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
this.execute();
|
||||
}
|
||||
|
||||
public V execute(){
|
||||
// JedisCluster, JedisPooled in fact is just UnifiedJedis does not need new instance since its single instance anyway.
|
||||
if (api.getMode() == RedisBungeeMode.SINGLE) {
|
||||
JedisPooledSummoner jedisSummoner = (JedisPooledSummoner) summoner;
|
||||
return this.unifiedJedisTask(jedisSummoner.obtainResource());
|
||||
} else if (api.getMode() == RedisBungeeMode.CLUSTER) {
|
||||
JedisClusterSummoner jedisClusterSummoner = (JedisClusterSummoner) summoner;
|
||||
return this.unifiedJedisTask(jedisClusterSummoner.obtainResource());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public RedisBungeePlugin<?> getPlugin() {
|
||||
if (plugin == null) {
|
||||
throw new NullPointerException("Plugin is null in the task");
|
||||
}
|
||||
return plugin;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.tasks;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.player.PlayerUtils;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisCluster;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class ShutdownUtils {
|
||||
|
||||
public static void shutdownCleanup(RedisBungeePlugin<?> plugin) {
|
||||
new RedisTask<Void>(plugin) {
|
||||
@Override
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
unifiedJedis.hdel("heartbeats", plugin.getConfiguration().getProxyId());
|
||||
if (unifiedJedis.scard("proxy:" + plugin.getConfiguration().getProxyId() + ":usersOnline") > 0) {
|
||||
Set<String> players = unifiedJedis.smembers("proxy:" + plugin.getConfiguration().getProxyId() + ":usersOnline");
|
||||
for (String member : players)
|
||||
PlayerUtils.cleanUpPlayer(member, unifiedJedis, true);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}.execute();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.api.util;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
|
||||
@VisibleForTesting
|
||||
public class RedisUtil {
|
||||
public final static int PROXY_TIMEOUT = 30;
|
||||
public static boolean isRedisVersionRight(String redisVersion) {
|
||||
String[] args = redisVersion.split("\\.");
|
||||
if (args.length < 2) {
|
||||
return false;
|
||||
}
|
||||
int major = Integer.parseInt(args[0]);
|
||||
int minor = Integer.parseInt(args[1]);
|
||||
return major >= 3 && minor >= 0;
|
||||
}
|
||||
|
||||
// Ham1255: i am keeping this if some plugin uses this *IF*
|
||||
@Deprecated
|
||||
public static boolean canUseLua(String redisVersion) {
|
||||
// Need to use >=3 to use Lua optimizations.
|
||||
return isRedisVersionRight(redisVersion);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal.util;
|
||||
package com.imaginarycode.minecraft.redisbungee.api.util.io;
|
||||
|
||||
import com.google.common.io.ByteStreams;
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.api.util.payload;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.imaginarycode.minecraft.redisbungee.AbstractRedisBungeeAPI;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.AbstractDataManager;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.UUID;
|
||||
|
||||
public class PayloadUtils {
|
||||
private static final Gson gson = new Gson();
|
||||
|
||||
public static void playerJoinPayload(UUID uuid, UnifiedJedis unifiedJedis, InetAddress inetAddress) {
|
||||
unifiedJedis.publish("redisbungee-data", gson.toJson(new AbstractDataManager.DataManagerMessage<>(
|
||||
uuid, AbstractRedisBungeeAPI.getAbstractRedisBungeeAPI().getProxyId(), AbstractDataManager.DataManagerMessage.Action.JOIN,
|
||||
new AbstractDataManager.LoginPayload(inetAddress))));
|
||||
}
|
||||
|
||||
|
||||
public static void playerQuitPayload(String uuid, UnifiedJedis unifiedJedis, long timestamp) {
|
||||
unifiedJedis.publish("redisbungee-data", gson.toJson(new AbstractDataManager.DataManagerMessage<>(
|
||||
UUID.fromString(uuid), AbstractRedisBungeeAPI.getAbstractRedisBungeeAPI().getProxyId(), AbstractDataManager.DataManagerMessage.Action.LEAVE,
|
||||
new AbstractDataManager.LogoutPayload(timestamp))));
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void playerServerChangePayload(UUID uuid, UnifiedJedis unifiedJedis, String newServer, String oldServer) {
|
||||
unifiedJedis.publish("redisbungee-data", gson.toJson(new AbstractDataManager.DataManagerMessage<>(
|
||||
uuid, AbstractRedisBungeeAPI.getAbstractRedisBungeeAPI().getProxyId(), AbstractDataManager.DataManagerMessage.Action.SERVER_CHANGE,
|
||||
new AbstractDataManager.ServerChangePayload(newServer, oldServer))));
|
||||
}
|
||||
|
||||
|
||||
public static void kickPlayerPayload(UUID uuid, String message, UnifiedJedis unifiedJedis) {
|
||||
unifiedJedis.publish("redisbungee-data", gson.toJson(new AbstractDataManager.DataManagerMessage<>(
|
||||
uuid, AbstractRedisBungeeAPI.getAbstractRedisBungeeAPI().getProxyId(), AbstractDataManager.DataManagerMessage.Action.KICK,
|
||||
new AbstractDataManager.KickPayload(message))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.api.util.player;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.AbstractRedisBungeeAPI;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static com.imaginarycode.minecraft.redisbungee.api.util.payload.PayloadUtils.playerJoinPayload;
|
||||
import static com.imaginarycode.minecraft.redisbungee.api.util.payload.PayloadUtils.playerQuitPayload;
|
||||
|
||||
public class PlayerUtils {
|
||||
|
||||
public static void cleanUpPlayer(String uuid, UnifiedJedis rsc, boolean firePayload) {
|
||||
final long timestamp = System.currentTimeMillis();
|
||||
final boolean isKickedFromOtherLocation = isKickedOtherLocation(uuid, rsc);
|
||||
rsc.srem("proxy:" + AbstractRedisBungeeAPI.getAbstractRedisBungeeAPI().getProxyId() + ":usersOnline", uuid);
|
||||
if (!isKickedFromOtherLocation) {
|
||||
rsc.hdel("player:" + uuid, "server", "ip", "proxy");
|
||||
rsc.hset("player:" + uuid, "online", String.valueOf(timestamp));
|
||||
}
|
||||
if (firePayload && !isKickedFromOtherLocation) {
|
||||
playerQuitPayload(uuid, rsc, timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
public static void setKickedOtherLocation(String uuid, UnifiedJedis unifiedJedis) {
|
||||
// set anything for sake of exists check. then expire it after 2 seconds. should be great?
|
||||
unifiedJedis.set("kicked-other-location::" + uuid, "0");
|
||||
unifiedJedis.expire("kicked-other-location::" + uuid, 2);
|
||||
}
|
||||
|
||||
public static boolean isKickedOtherLocation(String uuid, UnifiedJedis unifiedJedis) {
|
||||
return unifiedJedis.exists("kicked-other-location::" + uuid);
|
||||
}
|
||||
|
||||
|
||||
public static void createPlayer(UUID uuid, UnifiedJedis unifiedJedis, String currentServer, InetAddress hostname, boolean fireEvent) {
|
||||
final boolean isKickedFromOtherLocation = isKickedOtherLocation(uuid.toString(), unifiedJedis);
|
||||
Map<String, String> playerData = new HashMap<>(4);
|
||||
playerData.put("online", "0");
|
||||
playerData.put("ip", hostname.getHostName());
|
||||
playerData.put("proxy", AbstractRedisBungeeAPI.getAbstractRedisBungeeAPI().getProxyId());
|
||||
if (currentServer != null) {
|
||||
playerData.put("server", currentServer);
|
||||
}
|
||||
unifiedJedis.sadd("proxy:" + AbstractRedisBungeeAPI.getAbstractRedisBungeeAPI().getProxyId() + ":usersOnline", uuid.toString());
|
||||
unifiedJedis.hset("player:" + uuid, playerData);
|
||||
if (fireEvent && !isKickedFromOtherLocation) {
|
||||
playerJoinPayload(uuid, unifiedJedis, hostname);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.api.util.serialize;
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.collect.Multiset;
|
||||
import com.google.common.io.ByteArrayDataOutput;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
public class Serializations {
|
||||
|
||||
public static void serializeMultiset(Multiset<String> collection, ByteArrayDataOutput output) {
|
||||
output.writeInt(collection.elementSet().size());
|
||||
for (Multiset.Entry<String> entry : collection.entrySet()) {
|
||||
output.writeUTF(entry.getElement());
|
||||
output.writeInt(entry.getCount());
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("SameParameterValue")
|
||||
public static void serializeMultimap(Multimap<String, String> collection, boolean includeNames, ByteArrayDataOutput output) {
|
||||
output.writeInt(collection.keySet().size());
|
||||
for (Map.Entry<String, Collection<String>> entry : collection.asMap().entrySet()) {
|
||||
output.writeUTF(entry.getKey());
|
||||
if (includeNames) {
|
||||
serializeCollection(entry.getValue(), output);
|
||||
} else {
|
||||
output.writeInt(entry.getValue().size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void serializeCollection(Collection<?> collection, ByteArrayDataOutput output) {
|
||||
output.writeInt(collection.size());
|
||||
for (Object o : collection) {
|
||||
output.writeUTF(o.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.util.uuid;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.UUID;
|
||||
|
||||
public class CachedUUIDEntry {
|
||||
private final String name;
|
||||
private final UUID uuid;
|
||||
private final Calendar expiry;
|
||||
|
||||
public CachedUUIDEntry(String name, UUID uuid, Calendar expiry) {
|
||||
this.name = name;
|
||||
this.uuid = uuid;
|
||||
this.expiry = expiry;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public UUID getUuid() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public Calendar getExpiry() {
|
||||
return expiry;
|
||||
}
|
||||
|
||||
public boolean expired() {
|
||||
return Calendar.getInstance().after(expiry);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.util.uuid;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import com.squareup.okhttp.OkHttpClient;
|
||||
import com.squareup.okhttp.Request;
|
||||
import com.squareup.okhttp.ResponseBody;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Deprecated
|
||||
public class NameFetcher {
|
||||
private static OkHttpClient httpClient;
|
||||
private static final Gson gson = new Gson();
|
||||
|
||||
@Deprecated
|
||||
public static void setHttpClient(OkHttpClient httpClient) {
|
||||
throw new UnsupportedOperationException("Due mojang disabled the Names API NameFetcher no longer functions and has been disabled");
|
||||
// NameFetcher.httpClient = httpClient;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static List<String> nameHistoryFromUuid(UUID uuid) throws IOException {
|
||||
throw new UnsupportedOperationException("Due mojang disabled the Names API NameFetcher no longer functions and has been disabled");
|
||||
// String url = "https://api.mojang.com/user/profiles/" + uuid.toString().replace("-", "") + "/names";
|
||||
// Request request = new Request.Builder().url(url).get().build();
|
||||
// ResponseBody body = httpClient.newCall(request).execute().body();
|
||||
// String response = body.string();
|
||||
// body.close();
|
||||
//
|
||||
// Type listType = new TypeToken<List<Name>>() {
|
||||
// }.getType();
|
||||
// List<Name> names = gson.fromJson(response, listType);
|
||||
//
|
||||
// List<String> humanNames = new ArrayList<>();
|
||||
// for (Name name : names) {
|
||||
// humanNames.add(name.name);
|
||||
// }
|
||||
// return humanNames;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static class Name {
|
||||
private String name;
|
||||
private long changedToAt;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,14 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal.util.uuid;
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.util.uuid;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.gson.Gson;
|
||||
@@ -0,0 +1,212 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.api.util.uuid;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.gson.Gson;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.tasks.RedisTask;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
import redis.clients.jedis.exceptions.JedisException;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class UUIDTranslator {
|
||||
private static final Pattern UUID_PATTERN = Pattern.compile("[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}");
|
||||
private static final Pattern MOJANGIAN_UUID_PATTERN = Pattern.compile("[a-fA-F0-9]{32}");
|
||||
private final RedisBungeePlugin<?> plugin;
|
||||
private final Map<String, CachedUUIDEntry> nameToUuidMap = new ConcurrentHashMap<>(128, 0.5f, 4);
|
||||
private final Map<UUID, CachedUUIDEntry> uuidToNameMap = new ConcurrentHashMap<>(128, 0.5f, 4);
|
||||
private static final Gson gson = new Gson();
|
||||
|
||||
public UUIDTranslator(RedisBungeePlugin<?> plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
private void addToMaps(String name, UUID uuid) {
|
||||
// This is why I like LocalDate...
|
||||
|
||||
// Cache the entry for three days.
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.add(Calendar.DAY_OF_MONTH, 3);
|
||||
|
||||
// Create the entry and populate the local maps
|
||||
CachedUUIDEntry entry = new CachedUUIDEntry(name, uuid, calendar);
|
||||
nameToUuidMap.put(name.toLowerCase(), entry);
|
||||
uuidToNameMap.put(uuid, entry);
|
||||
}
|
||||
|
||||
public UUID getTranslatedUuid(@NonNull String player, boolean expensiveLookups) {
|
||||
// If the player is online, give them their UUID.
|
||||
// Remember, local data > remote data.
|
||||
if (plugin.getPlayer(player) != null)
|
||||
return plugin.getPlayerUUID(player);
|
||||
|
||||
// Check if it exists in the map
|
||||
CachedUUIDEntry cachedUUIDEntry = nameToUuidMap.get(player.toLowerCase());
|
||||
if (cachedUUIDEntry != null) {
|
||||
if (!cachedUUIDEntry.expired())
|
||||
return cachedUUIDEntry.getUuid();
|
||||
else
|
||||
nameToUuidMap.remove(player);
|
||||
}
|
||||
|
||||
// Check if we can exit early
|
||||
if (UUID_PATTERN.matcher(player).find()) {
|
||||
return UUID.fromString(player);
|
||||
}
|
||||
|
||||
if (MOJANGIAN_UUID_PATTERN.matcher(player).find()) {
|
||||
// Reconstruct the UUID
|
||||
return UUIDFetcher.getUUID(player);
|
||||
}
|
||||
|
||||
// If we are in offline mode, UUID generation is simple.
|
||||
// We don't even have to cache the UUID, since this is easy to recalculate.
|
||||
if (!plugin.isOnlineMode()) {
|
||||
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player).getBytes(Charsets.UTF_8));
|
||||
}
|
||||
RedisTask<UUID> redisTask = new RedisTask<UUID>(plugin) {
|
||||
@Override
|
||||
public UUID unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
String stored = unifiedJedis.hget("uuid-cache", player.toLowerCase());
|
||||
if (stored != null) {
|
||||
// Found an entry value. Deserialize it.
|
||||
CachedUUIDEntry entry = gson.fromJson(stored, CachedUUIDEntry.class);
|
||||
|
||||
// Check for expiry:
|
||||
if (entry.expired()) {
|
||||
unifiedJedis.hdel("uuid-cache", player.toLowerCase());
|
||||
// Doesn't hurt to also remove the UUID entry as well.
|
||||
unifiedJedis.hdel("uuid-cache", entry.getUuid().toString());
|
||||
} else {
|
||||
nameToUuidMap.put(player.toLowerCase(), entry);
|
||||
uuidToNameMap.put(entry.getUuid(), entry);
|
||||
return entry.getUuid();
|
||||
}
|
||||
}
|
||||
|
||||
// That didn't work. Let's ask Mojang.
|
||||
if (!expensiveLookups || !plugin.isOnlineMode())
|
||||
return null;
|
||||
|
||||
Map<String, UUID> uuidMap1;
|
||||
try {
|
||||
uuidMap1 = new UUIDFetcher(Collections.singletonList(player)).call();
|
||||
} catch (Exception e) {
|
||||
plugin.logFatal("Unable to fetch UUID from Mojang for " + player);
|
||||
return null;
|
||||
}
|
||||
for (Map.Entry<String, UUID> entry : uuidMap1.entrySet()) {
|
||||
if (entry.getKey().equalsIgnoreCase(player)) {
|
||||
persistInfo(entry.getKey(), entry.getValue(), unifiedJedis);
|
||||
return entry.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
// Let's try Redis.
|
||||
try {
|
||||
return redisTask.execute();
|
||||
} catch (JedisException e) {
|
||||
plugin.logFatal("Unable to fetch UUID for " + player);
|
||||
}
|
||||
|
||||
return null; // Nope, game over!
|
||||
}
|
||||
|
||||
public String getNameFromUuid(@NonNull UUID player, boolean expensiveLookups) {
|
||||
// If the player is online, give them their UUID.
|
||||
// Remember, local data > remote data.
|
||||
if (plugin.getPlayer(player) != null)
|
||||
return plugin.getPlayerName(player);
|
||||
|
||||
// Check if it exists in the map
|
||||
CachedUUIDEntry cachedUUIDEntry = uuidToNameMap.get(player);
|
||||
if (cachedUUIDEntry != null) {
|
||||
if (!cachedUUIDEntry.expired())
|
||||
return cachedUUIDEntry.getName();
|
||||
else
|
||||
uuidToNameMap.remove(player);
|
||||
}
|
||||
|
||||
RedisTask<String> redisTask = new RedisTask<String>(plugin) {
|
||||
@Override
|
||||
public String unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
String stored = unifiedJedis.hget("uuid-cache", player.toString());
|
||||
if (stored != null) {
|
||||
// Found an entry value. Deserialize it.
|
||||
CachedUUIDEntry entry = gson.fromJson(stored, CachedUUIDEntry.class);
|
||||
|
||||
// Check for expiry:
|
||||
if (entry.expired()) {
|
||||
unifiedJedis.hdel("uuid-cache", player.toString());
|
||||
// Doesn't hurt to also remove the named entry as well.
|
||||
// TODO: Since UUIDs are fixed, we could look up the name and see if the UUID matches.
|
||||
unifiedJedis.hdel("uuid-cache", entry.getName());
|
||||
} else {
|
||||
nameToUuidMap.put(entry.getName().toLowerCase(), entry);
|
||||
uuidToNameMap.put(player, entry);
|
||||
return entry.getName();
|
||||
}
|
||||
}
|
||||
|
||||
if (!expensiveLookups || !plugin.isOnlineMode())
|
||||
return null;
|
||||
|
||||
// That didn't work. Let's ask Mojang. This call may fail, because Mojang is insane.
|
||||
//
|
||||
// UPDATE: Mojang has removed the API somewhere in september/2022 due privacy issues
|
||||
// this is expected to fail now, so we will keep logging it until we figure out something or remove name fetching completely
|
||||
// Name fetching class was deprecated as result
|
||||
String name;
|
||||
try {
|
||||
plugin.logFatal("Due Mojang removing the naming API, we were unable to fetch player names.");
|
||||
name = Iterables.getLast(NameFetcher.nameHistoryFromUuid(player));
|
||||
} catch (Exception e) {
|
||||
plugin.logFatal("Unable to fetch name from Mojang for " + player);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (name != null) {
|
||||
persistInfo(name, player, unifiedJedis);
|
||||
return name;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Okay, it wasn't locally cached. Let's try Redis.
|
||||
try {
|
||||
return redisTask.execute();
|
||||
} catch (JedisException e) {
|
||||
plugin.logFatal("Unable to fetch name for " + player);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void persistInfo(String name, UUID uuid, UnifiedJedis unifiedJedis) {
|
||||
addToMaps(name, uuid);
|
||||
String json = gson.toJson(uuidToNameMap.get(uuid));
|
||||
unifiedJedis.hset("uuid-cache", ImmutableMap.of(name.toLowerCase(), json, uuid.toString(), json));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal;
|
||||
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.collect.Multiset;
|
||||
import com.google.common.io.ByteArrayDataOutput;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public abstract class AbstractRedisBungeeListener<LE, PLE, PD, SC, PP, PM, PS> {
|
||||
|
||||
protected static final String ALREADY_LOGGED_IN = "§cYou are already logged on to this server. \n\nIt may help to try logging in again in a few minutes.\nIf this does not resolve your issue, please contact staff.";
|
||||
|
||||
protected static final String ONLINE_MODE_RECONNECT = "§cWhoops! You need to reconnect\n\nWe found someone online using your username. They were kicked and you may reconnect.\nIf this does not work, please contact staff.";
|
||||
|
||||
protected final RedisBungeePlugin<?> plugin;
|
||||
protected final List<InetAddress> exemptAddresses;
|
||||
protected final Gson gson = new Gson();
|
||||
|
||||
public AbstractRedisBungeeListener(RedisBungeePlugin<?> plugin, List<InetAddress> exemptAddresses) {
|
||||
this.plugin = plugin;
|
||||
this.exemptAddresses = exemptAddresses;
|
||||
}
|
||||
|
||||
public abstract void onLogin(LE event);
|
||||
|
||||
public abstract void onPostLogin(PLE event);
|
||||
|
||||
public abstract void onPlayerDisconnect(PD event);
|
||||
|
||||
public abstract void onServerChange(SC event);
|
||||
|
||||
public abstract void onPing(PP event);
|
||||
|
||||
public abstract void onPluginMessage(PM event);
|
||||
|
||||
protected void serializeMultiset(Multiset<String> collection, ByteArrayDataOutput output) {
|
||||
output.writeInt(collection.elementSet().size());
|
||||
for (Multiset.Entry<String> entry : collection.entrySet()) {
|
||||
output.writeUTF(entry.getElement());
|
||||
output.writeInt(entry.getCount());
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("SameParameterValue")
|
||||
protected void serializeMultimap(Multimap<String, String> collection, boolean includeNames, ByteArrayDataOutput output) {
|
||||
output.writeInt(collection.keySet().size());
|
||||
for (Map.Entry<String, Collection<String>> entry : collection.asMap().entrySet()) {
|
||||
output.writeUTF(entry.getKey());
|
||||
if (includeNames) {
|
||||
serializeCollection(entry.getValue(), output);
|
||||
} else {
|
||||
output.writeInt(entry.getValue().size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void serializeCollection(Collection<?> collection, ByteArrayDataOutput output) {
|
||||
output.writeInt(collection.size());
|
||||
for (Object o : collection) {
|
||||
output.writeUTF(o.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public abstract void onPubSubMessage(PS event);
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal;
|
||||
|
||||
/**
|
||||
* Since each platform have their own events' implementation for example Bungeecord events extends Event while velocity don't
|
||||
*
|
||||
* @author Ham1255
|
||||
* @since 0.7.0
|
||||
*
|
||||
*/
|
||||
public interface EventsPlatform {
|
||||
|
||||
Class<?> getPubSubEventClass();
|
||||
|
||||
Class<?> getNetworkJoinEventClass();
|
||||
|
||||
Class<?> getServerChangeEventClass();
|
||||
|
||||
Class<?> getNetworkQuitEventClass();
|
||||
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal;
|
||||
|
||||
|
||||
import redis.clients.jedis.JedisPubSub;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
|
||||
|
||||
public class JedisPubSubHandler extends JedisPubSub {
|
||||
|
||||
private final RedisBungeePlugin<?> plugin;
|
||||
private final Class<?> eventClass;
|
||||
public JedisPubSubHandler(RedisBungeePlugin<?> plugin) {
|
||||
this.plugin = plugin;
|
||||
this.eventClass = plugin.getPubSubEventClass();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(final String s, final String s2) {
|
||||
if (s2.trim().length() == 0) return;
|
||||
plugin.executeAsync(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Object event;
|
||||
try {
|
||||
event = eventClass.getDeclaredConstructor(String.class, String.class).newInstance(s, s2);
|
||||
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
|
||||
throw new RuntimeException("unable to dispatch an pubsub event", e);
|
||||
}
|
||||
plugin.callEvent(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal;
|
||||
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
|
||||
|
||||
/**
|
||||
* This class intended for future release to support redis sentinel or redis clusters
|
||||
*
|
||||
* @author Ham1255
|
||||
* @since 0.7.0
|
||||
*
|
||||
*/
|
||||
public interface JedisSummoner {
|
||||
|
||||
Jedis requestJedis();
|
||||
|
||||
boolean isJedisAvailable();
|
||||
|
||||
@Deprecated
|
||||
JedisPool getJedisPool();
|
||||
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.net.InetAddresses;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.List;
|
||||
|
||||
public class RedisBungeeConfiguration {
|
||||
private final String serverId;
|
||||
private final List<InetAddress> exemptAddresses;
|
||||
private final boolean overrideBungeeCommands;
|
||||
private static RedisBungeeConfiguration config;
|
||||
|
||||
public RedisBungeeConfiguration(String serverId, List<String> exemptAddresses, boolean overrideBungeeCommands) {
|
||||
this.serverId = serverId;
|
||||
|
||||
ImmutableList.Builder<InetAddress> addressBuilder = ImmutableList.builder();
|
||||
for (String s : exemptAddresses) {
|
||||
addressBuilder.add(InetAddresses.forString(s));
|
||||
}
|
||||
this.exemptAddresses = addressBuilder.build();
|
||||
config = this;
|
||||
this.overrideBungeeCommands = overrideBungeeCommands;
|
||||
}
|
||||
|
||||
public String getServerId() {
|
||||
return serverId;
|
||||
}
|
||||
|
||||
public List<InetAddress> getExemptAddresses() {
|
||||
return exemptAddresses;
|
||||
}
|
||||
|
||||
public boolean doOverrideBungeeCommands() {
|
||||
return overrideBungeeCommands;
|
||||
}
|
||||
|
||||
public static RedisBungeeConfiguration getConfig() {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal;
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.imaginarycode.minecraft.redisbungee.RedisBungeeAPI;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.util.uuid.UUIDTranslator;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* This Class has all internal methods needed by every redis bungee plugin, and it can be used to implement another platforms than bungeecord
|
||||
*
|
||||
* @author Ham1255
|
||||
* @since 0.7.0
|
||||
*
|
||||
*/
|
||||
public interface RedisBungeePlugin<P> extends JedisSummoner, EventsPlatform{
|
||||
|
||||
default void enable() {
|
||||
|
||||
}
|
||||
|
||||
default void disable() {
|
||||
|
||||
}
|
||||
|
||||
RedisBungeeConfiguration getConfiguration();
|
||||
|
||||
int getCount();
|
||||
|
||||
int getCurrentCount();
|
||||
|
||||
Set<String> getLocalPlayersAsUuidStrings();
|
||||
|
||||
DataManager<P, ?, ?, ?> getDataManager();
|
||||
|
||||
Set<UUID> getPlayers();
|
||||
|
||||
RedisBungeeAPI getApi();
|
||||
|
||||
UUIDTranslator getUuidTranslator();
|
||||
|
||||
Multimap<String, UUID> serversToPlayers();
|
||||
|
||||
Set<UUID> getPlayersOnProxy(String proxyId);
|
||||
|
||||
void sendProxyCommand(String serverId, String command);
|
||||
|
||||
List<String> getServerIds();
|
||||
|
||||
List<String > getCurrentServerIds(boolean nag, boolean lagged);
|
||||
|
||||
PubSubListener getPubSubListener();
|
||||
|
||||
void sendChannelMessage(String channel, String message);
|
||||
|
||||
void executeAsync(Runnable runnable);
|
||||
|
||||
void executeAsyncAfter(Runnable runnable, TimeUnit timeUnit, int time);
|
||||
|
||||
void callEvent(Object event);
|
||||
|
||||
boolean isOnlineMode();
|
||||
|
||||
void logInfo(String msg);
|
||||
|
||||
void logWarn(String msg);
|
||||
|
||||
void logFatal(String msg);
|
||||
|
||||
P getPlayer(UUID uuid);
|
||||
|
||||
P getPlayer(String name);
|
||||
|
||||
UUID getPlayerUUID(String player);
|
||||
|
||||
String getPlayerName(UUID player);
|
||||
|
||||
String getPlayerServerName(P player);
|
||||
|
||||
boolean isPlayerOnAServer(P player);
|
||||
|
||||
InetAddress getPlayerIp(P player);
|
||||
|
||||
void sendProxyCommand(String cmd);
|
||||
|
||||
long getRedisTime(List<String> timeRes);
|
||||
|
||||
void loadConfig() throws Exception;
|
||||
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.gson.Gson;
|
||||
import com.imaginarycode.minecraft.redisbungee.RedisBungeeAPI;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.Pipeline;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@VisibleForTesting
|
||||
public class RedisUtil {
|
||||
private static final Gson gson = new Gson();
|
||||
|
||||
public static void cleanUpPlayer(String player, Jedis rsc) {
|
||||
rsc.srem("proxy:" + RedisBungeeAPI.getRedisBungeeApi().getServerId() + ":usersOnline", player);
|
||||
rsc.hdel("player:" + player, "server", "ip", "proxy");
|
||||
long timestamp = System.currentTimeMillis();
|
||||
rsc.hset("player:" + player, "online", String.valueOf(timestamp));
|
||||
rsc.publish("redisbungee-data", gson.toJson(new DataManager.DataManagerMessage<>(
|
||||
UUID.fromString(player), RedisBungeeAPI.getRedisBungeeApi().getServerId(), DataManager.DataManagerMessage.Action.LEAVE,
|
||||
new DataManager.LogoutPayload(timestamp))));
|
||||
}
|
||||
|
||||
public static void cleanUpPlayer(String player, Pipeline rsc) {
|
||||
rsc.srem("proxy:" + RedisBungeeAPI.getRedisBungeeApi().getServerId() + ":usersOnline", player);
|
||||
rsc.hdel("player:" + player, "server", "ip", "proxy");
|
||||
long timestamp = System.currentTimeMillis();
|
||||
rsc.hset("player:" + player, "online", String.valueOf(timestamp));
|
||||
rsc.publish("redisbungee-data", gson.toJson(new DataManager.DataManagerMessage<>(
|
||||
UUID.fromString(player), RedisBungeeAPI.getRedisBungeeApi().getServerId(), DataManager.DataManagerMessage.Action.LEAVE,
|
||||
new DataManager.LogoutPayload(timestamp))));
|
||||
}
|
||||
|
||||
public static boolean isRedisVersionRight(String redisVersion) {
|
||||
// Need to use >=6.2 to use Lua optimizations.
|
||||
String[] args = redisVersion.split("\\.");
|
||||
if (args.length < 2) {
|
||||
return false;
|
||||
}
|
||||
int major = Integer.parseInt(args[0]);
|
||||
int minor = Integer.parseInt(args[1]);
|
||||
return major >= 6 && minor >= 0;
|
||||
}
|
||||
|
||||
// Ham1255: i am keeping this if some plugin uses this *IF*
|
||||
@Deprecated
|
||||
public static boolean canUseLua(String redisVersion) {
|
||||
return isRedisVersionRight(redisVersion);
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal.util;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.RedisBungeePlugin;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.exceptions.JedisDataException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class LuaManager {
|
||||
private final RedisBungeePlugin<?> plugin;
|
||||
|
||||
public LuaManager(RedisBungeePlugin<?> plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public Script createScript(String script) {
|
||||
try (Jedis jedis = plugin.requestJedis()) {
|
||||
String hash = jedis.scriptLoad(script);
|
||||
return new Script(script, hash);
|
||||
}
|
||||
}
|
||||
|
||||
public class Script {
|
||||
private final String script;
|
||||
private final String hashed;
|
||||
|
||||
public Script(String script, String hashed) {
|
||||
this.script = script;
|
||||
this.hashed = hashed;
|
||||
}
|
||||
|
||||
public String getScript() {
|
||||
return script;
|
||||
}
|
||||
|
||||
public String getHashed() {
|
||||
return hashed;
|
||||
}
|
||||
|
||||
public Object eval(List<String> keys, List<String> args) {
|
||||
Object data;
|
||||
|
||||
try (Jedis jedis = plugin.requestJedis()) {
|
||||
try {
|
||||
data = jedis.evalsha(hashed, keys, args);
|
||||
} catch (JedisDataException e) {
|
||||
if (e.getMessage().startsWith("NOSCRIPT")) {
|
||||
data = jedis.eval(script, keys, args);
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal.util;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.RedisBungeePlugin;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.exceptions.JedisConnectionException;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
|
||||
|
||||
public abstract class RedisCallable<T> implements Callable<T>, Runnable {
|
||||
private final RedisBungeePlugin<?> plugin;
|
||||
|
||||
public RedisCallable(RedisBungeePlugin<?> plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T call() {
|
||||
return run(false);
|
||||
}
|
||||
|
||||
public void run() {
|
||||
call();
|
||||
}
|
||||
|
||||
private T run(boolean retry) {
|
||||
try (Jedis jedis = plugin.requestJedis()) {
|
||||
return call(jedis);
|
||||
} catch (JedisConnectionException e) {
|
||||
plugin.logFatal("Unable to get connection");
|
||||
|
||||
if (!retry) {
|
||||
// Wait one second before retrying the task
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e1) {
|
||||
throw new RuntimeException("task failed to run", e1);
|
||||
}
|
||||
return run(true);
|
||||
}
|
||||
}
|
||||
|
||||
throw new RuntimeException("task failed to run");
|
||||
}
|
||||
|
||||
protected abstract T call(Jedis jedis);
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal.util.uuid;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import com.squareup.okhttp.OkHttpClient;
|
||||
import com.squareup.okhttp.Request;
|
||||
import com.squareup.okhttp.ResponseBody;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public class NameFetcher {
|
||||
private static OkHttpClient httpClient;
|
||||
private static final Gson gson = new Gson();
|
||||
|
||||
public static void setHttpClient(OkHttpClient httpClient) {
|
||||
NameFetcher.httpClient = httpClient;
|
||||
}
|
||||
|
||||
public static List<String> nameHistoryFromUuid(UUID uuid) throws IOException {
|
||||
String url = "https://api.mojang.com/user/profiles/" + uuid.toString().replace("-", "") + "/names";
|
||||
Request request = new Request.Builder().url(url).get().build();
|
||||
ResponseBody body = httpClient.newCall(request).execute().body();
|
||||
String response = body.string();
|
||||
body.close();
|
||||
|
||||
Type listType = new TypeToken<List<Name>>() {
|
||||
}.getType();
|
||||
List<Name> names = gson.fromJson(response, listType);
|
||||
|
||||
List<String> humanNames = new ArrayList<>();
|
||||
for (Name name : names) {
|
||||
humanNames.add(name.name);
|
||||
}
|
||||
return humanNames;
|
||||
}
|
||||
|
||||
public static class Name {
|
||||
private String name;
|
||||
private long changedToAt;
|
||||
}
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee.internal.util.uuid;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.gson.Gson;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.RedisBungeePlugin;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.Pipeline;
|
||||
import redis.clients.jedis.exceptions.JedisException;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.logging.Level;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class UUIDTranslator {
|
||||
private static final Pattern UUID_PATTERN = Pattern.compile("[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}");
|
||||
private static final Pattern MOJANGIAN_UUID_PATTERN = Pattern.compile("[a-fA-F0-9]{32}");
|
||||
private final RedisBungeePlugin<?> plugin;
|
||||
private final Map<String, CachedUUIDEntry> nameToUuidMap = new ConcurrentHashMap<>(128, 0.5f, 4);
|
||||
private final Map<UUID, CachedUUIDEntry> uuidToNameMap = new ConcurrentHashMap<>(128, 0.5f, 4);
|
||||
private static final Gson gson = new Gson();
|
||||
|
||||
public UUIDTranslator(RedisBungeePlugin<?> plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
private void addToMaps(String name, UUID uuid) {
|
||||
// This is why I like LocalDate...
|
||||
|
||||
// Cache the entry for three days.
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.add(Calendar.DAY_OF_MONTH, 3);
|
||||
|
||||
// Create the entry and populate the local maps
|
||||
CachedUUIDEntry entry = new CachedUUIDEntry(name, uuid, calendar);
|
||||
nameToUuidMap.put(name.toLowerCase(), entry);
|
||||
uuidToNameMap.put(uuid, entry);
|
||||
}
|
||||
|
||||
public final UUID getTranslatedUuid(@NonNull String player, boolean expensiveLookups) {
|
||||
// If the player is online, give them their UUID.
|
||||
// Remember, local data > remote data.
|
||||
if (plugin.getPlayer(player) != null)
|
||||
return plugin.getPlayerUUID(player);
|
||||
|
||||
// Check if it exists in the map
|
||||
CachedUUIDEntry cachedUUIDEntry = nameToUuidMap.get(player.toLowerCase());
|
||||
if (cachedUUIDEntry != null) {
|
||||
if (!cachedUUIDEntry.expired())
|
||||
return cachedUUIDEntry.getUuid();
|
||||
else
|
||||
nameToUuidMap.remove(player);
|
||||
}
|
||||
|
||||
// Check if we can exit early
|
||||
if (UUID_PATTERN.matcher(player).find()) {
|
||||
return UUID.fromString(player);
|
||||
}
|
||||
|
||||
if (MOJANGIAN_UUID_PATTERN.matcher(player).find()) {
|
||||
// Reconstruct the UUID
|
||||
return UUIDFetcher.getUUID(player);
|
||||
}
|
||||
|
||||
// If we are in offline mode, UUID generation is simple.
|
||||
// We don't even have to cache the UUID, since this is easy to recalculate.
|
||||
if (!plugin.isOnlineMode()) {
|
||||
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player).getBytes(Charsets.UTF_8));
|
||||
}
|
||||
|
||||
// Let's try Redis.
|
||||
try (Jedis jedis = plugin.requestJedis()) {
|
||||
String stored = jedis.hget("uuid-cache", player.toLowerCase());
|
||||
if (stored != null) {
|
||||
// Found an entry value. Deserialize it.
|
||||
CachedUUIDEntry entry = gson.fromJson(stored, CachedUUIDEntry.class);
|
||||
|
||||
// Check for expiry:
|
||||
if (entry.expired()) {
|
||||
jedis.hdel("uuid-cache", player.toLowerCase());
|
||||
// Doesn't hurt to also remove the UUID entry as well.
|
||||
jedis.hdel("uuid-cache", entry.getUuid().toString());
|
||||
} else {
|
||||
nameToUuidMap.put(player.toLowerCase(), entry);
|
||||
uuidToNameMap.put(entry.getUuid(), entry);
|
||||
return entry.getUuid();
|
||||
}
|
||||
}
|
||||
|
||||
// That didn't work. Let's ask Mojang.
|
||||
if (!expensiveLookups || !plugin.isOnlineMode())
|
||||
return null;
|
||||
|
||||
Map<String, UUID> uuidMap1;
|
||||
try {
|
||||
uuidMap1 = new UUIDFetcher(Collections.singletonList(player)).call();
|
||||
} catch (Exception e) {
|
||||
plugin.logFatal("Unable to fetch UUID from Mojang for " + player);
|
||||
return null;
|
||||
}
|
||||
for (Map.Entry<String, UUID> entry : uuidMap1.entrySet()) {
|
||||
if (entry.getKey().equalsIgnoreCase(player)) {
|
||||
persistInfo(entry.getKey(), entry.getValue(), jedis);
|
||||
return entry.getValue();
|
||||
}
|
||||
}
|
||||
} catch (JedisException e) {
|
||||
plugin.logFatal("Unable to fetch UUID for " + player);
|
||||
}
|
||||
|
||||
return null; // Nope, game over!
|
||||
}
|
||||
|
||||
public final String getNameFromUuid(@NonNull UUID player, boolean expensiveLookups) {
|
||||
// If the player is online, give them their UUID.
|
||||
// Remember, local data > remote data.
|
||||
if (plugin.getPlayer(player) != null)
|
||||
return plugin.getPlayerName(player);
|
||||
|
||||
// Check if it exists in the map
|
||||
CachedUUIDEntry cachedUUIDEntry = uuidToNameMap.get(player);
|
||||
if (cachedUUIDEntry != null) {
|
||||
if (!cachedUUIDEntry.expired())
|
||||
return cachedUUIDEntry.getName();
|
||||
else
|
||||
uuidToNameMap.remove(player);
|
||||
}
|
||||
|
||||
// Okay, it wasn't locally cached. Let's try Redis.
|
||||
try (Jedis jedis = plugin.requestJedis()) {
|
||||
String stored = jedis.hget("uuid-cache", player.toString());
|
||||
if (stored != null) {
|
||||
// Found an entry value. Deserialize it.
|
||||
CachedUUIDEntry entry = gson.fromJson(stored, CachedUUIDEntry.class);
|
||||
|
||||
// Check for expiry:
|
||||
if (entry.expired()) {
|
||||
jedis.hdel("uuid-cache", player.toString());
|
||||
// Doesn't hurt to also remove the named entry as well.
|
||||
// TODO: Since UUIDs are fixed, we could look up the name and see if the UUID matches.
|
||||
jedis.hdel("uuid-cache", entry.getName());
|
||||
} else {
|
||||
nameToUuidMap.put(entry.getName().toLowerCase(), entry);
|
||||
uuidToNameMap.put(player, entry);
|
||||
return entry.getName();
|
||||
}
|
||||
}
|
||||
|
||||
if (!expensiveLookups || !plugin.isOnlineMode())
|
||||
return null;
|
||||
|
||||
// That didn't work. Let's ask Mojang. This call may fail, because Mojang is insane.
|
||||
String name;
|
||||
try {
|
||||
List<String> nameHist = NameFetcher.nameHistoryFromUuid(player);
|
||||
name = Iterables.getLast(nameHist, null);
|
||||
} catch (Exception e) {
|
||||
plugin.logFatal("Unable to fetch name from Mojang for " + player);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (name != null) {
|
||||
persistInfo(name, player, jedis);
|
||||
return name;
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (JedisException e) {
|
||||
plugin.logFatal("Unable to fetch name for " + player);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public final void persistInfo(String name, UUID uuid, Jedis jedis) {
|
||||
addToMaps(name, uuid);
|
||||
String json = gson.toJson(uuidToNameMap.get(uuid));
|
||||
jedis.hmset("uuid-cache", ImmutableMap.of(name.toLowerCase(), json, uuid.toString(), json));
|
||||
}
|
||||
|
||||
public final void persistInfo(String name, UUID uuid, Pipeline jedis) {
|
||||
addToMaps(name, uuid);
|
||||
String json = gson.toJson(uuidToNameMap.get(uuid));
|
||||
jedis.hmset("uuid-cache", ImmutableMap.of(name.toLowerCase(), json, uuid.toString(), json));
|
||||
}
|
||||
|
||||
private static class CachedUUIDEntry {
|
||||
private final String name;
|
||||
private final UUID uuid;
|
||||
private final Calendar expiry;
|
||||
|
||||
public CachedUUIDEntry(String name, UUID uuid, Calendar expiry) {
|
||||
this.name = name;
|
||||
this.uuid = uuid;
|
||||
this.expiry = expiry;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public UUID getUuid() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public Calendar getExpiry() {
|
||||
return expiry;
|
||||
}
|
||||
|
||||
public boolean expired() {
|
||||
return Calendar.getInstance().after(expiry);
|
||||
}
|
||||
}
|
||||
}
|
||||
82
RedisBungee-API/src/main/resources/config.yml
Normal file
82
RedisBungee-API/src/main/resources/config.yml
Normal file
@@ -0,0 +1,82 @@
|
||||
# RedisBungee configuration file.
|
||||
# Get Redis from http://redis.io/
|
||||
|
||||
# The Redis server you use.
|
||||
# these settings are ignored when cluster mode is enabled.
|
||||
redis-server: 127.0.0.1
|
||||
redis-port: 6379
|
||||
|
||||
# Cluster Mode
|
||||
# enabling this option will enable cluster mode.
|
||||
cluster-mode-enabled: false
|
||||
|
||||
# FORMAT:
|
||||
# redis-cluster-servers:
|
||||
# - host: 127.0.0.1
|
||||
# port: 2020
|
||||
# - host: 127.0.0.1
|
||||
# port: 2021
|
||||
# - host: 127.0.0.1
|
||||
# port: 2021
|
||||
|
||||
# you can set single server and Jedis will automatically discover cluster nodes,
|
||||
# but might fail if this single redis node is down when Proxy startup, its recommended put the all the nodes
|
||||
redis-cluster-servers:
|
||||
- host: 127.0.0.1
|
||||
port: 6379
|
||||
|
||||
# THIS FEATURE IS REDIS V6+
|
||||
# OPTIONAL: if your redis uses acl usernames set the username here. leave empty for no username.
|
||||
redis-username: ""
|
||||
|
||||
# OPTIONAL but recommended: If your Redis server uses AUTH, set the password required.
|
||||
redis-password: ""
|
||||
|
||||
# Maximum connections that will be maintained to the Redis server.
|
||||
# The default is 10. This setting should be left as-is unless you have some wildly
|
||||
# inefficient plugins or a lot of players.
|
||||
max-redis-connections: 10
|
||||
|
||||
# since redis can support ssl by version 6 you can use ssl / tls in redis bungee too!
|
||||
# but there is more configuration needed to work see https://github.com/ProxioDev/RedisBungee/issues/18
|
||||
# Keep note that SSL/TLS connections will decrease redis performance so use it when needed.
|
||||
useSSL: false
|
||||
|
||||
# An identifier for this BungeeCord / Velocity instance. Will randomly generate if leaving it blank.
|
||||
proxy-id: "test-1"
|
||||
|
||||
# since version 0.8.0 Internally now uses JedisPooled instead of Jedis, JedisPool.
|
||||
# which will break compatibility with old plugins that uses RedisBungee JedisPool
|
||||
# so to mitigate this issue, we will instruct RedisBungee to init an JedisPool for compatibility reasons.
|
||||
# enabled by default
|
||||
# ignored when cluster mode is enabled
|
||||
enable-jedis-pool-compatibility: true
|
||||
# max connections for the compatibility pool
|
||||
compatibility-max-connections: 3
|
||||
|
||||
# Register redis bungee legacy commands
|
||||
# if this disabled override-bungee-commands will be ignored
|
||||
register-legacy-commands: false
|
||||
|
||||
# Whether or not RedisBungee should install its version of regular BungeeCord commands.
|
||||
# Often, the RedisBungee commands are desired, but in some cases someone may wish to
|
||||
# override the commands using another plugin.
|
||||
#
|
||||
# If you are just denying access to the commands, RedisBungee uses the default BungeeCord
|
||||
# permissions - just deny them and access will be denied.
|
||||
#
|
||||
# Please note that with build 787+, most commands overridden by RedisBungee were moved to
|
||||
# modules, and these must be disabled or overridden yourself.
|
||||
override-bungee-commands: false
|
||||
|
||||
# A list of IP addresses for which RedisBungee will not modify the response for, useful for automatic
|
||||
# restart scripts.
|
||||
exempt-ip-addresses: []
|
||||
|
||||
# restore old login when online behavior before 0.9.0 update
|
||||
# uncomment to enable it
|
||||
|
||||
# disable-kick-when-online: true
|
||||
|
||||
# Config version DO NOT CHANGE!!!!
|
||||
config-version: 1
|
||||
@@ -1,35 +0,0 @@
|
||||
# RedisBungee configuration file.
|
||||
# PLEASE READ THE WIKI: https://github.com/Limework/RedisBungee/wiki
|
||||
|
||||
# The Redis server you use.
|
||||
# Get Redis from http://redis.io/
|
||||
redis-server: 127.0.0.1
|
||||
redis-port: 6379
|
||||
# OPTIONAL but recommended: If your Redis server uses AUTH, set the password required.
|
||||
redis-password: ""
|
||||
# Maximum connections that will be maintained to the Redis server.
|
||||
# The default is 10. This setting should be left as-is unless you have some wildly
|
||||
# inefficient plugins or a lot of players.
|
||||
max-redis-connections: 10
|
||||
|
||||
# since redis can support ssl by version 6 you can use ssl in redis bungee too!
|
||||
# but there is more configuration needed to work see https://github.com/ProxioDev/RedisBungee/issues/18
|
||||
useSSL: false
|
||||
|
||||
# An identifier for this BungeeCord instance. Will randomly generate if leaving it blank.
|
||||
server-id: "test1"
|
||||
|
||||
# Whether or not RedisBungee should install its version of regular BungeeCord commands.
|
||||
# Often, the RedisBungee commands are desired, but in some cases someone may wish to
|
||||
# override the commands using another plugin.
|
||||
#
|
||||
# If you are just denying access to the commands, RedisBungee uses the default BungeeCord
|
||||
# permissions - just deny them and access will be denied.
|
||||
#
|
||||
# Please note that with build 787+, most commands overridden by RedisBungee were moved to
|
||||
# modules, and these must be disabled or overridden yourself.
|
||||
register-bungee-commands: true
|
||||
|
||||
# A list of IP addresses for which RedisBungee will not modify the response for, useful for automatic
|
||||
# restart scripts.
|
||||
exempt-ip-addresses: []
|
||||
@@ -1,24 +0,0 @@
|
||||
local c = redis.call
|
||||
|
||||
local curTime = c("TIME")
|
||||
local time = tonumber(curTime[1])
|
||||
|
||||
local heartbeats = c("HGETALL", "heartbeats")
|
||||
local total = 0
|
||||
local key
|
||||
|
||||
for _, v in ipairs(heartbeats) do
|
||||
if not key then
|
||||
key = v
|
||||
else
|
||||
local n = tonumber(v)
|
||||
if n then
|
||||
if n + 30 >= time then
|
||||
total = total + c("SCARD", "proxy:" .. key .. ":usersOnline")
|
||||
end
|
||||
end
|
||||
key = nil
|
||||
end
|
||||
end
|
||||
|
||||
return total
|
||||
@@ -1,18 +0,0 @@
|
||||
local call = redis.call
|
||||
local ipairs = ipairs
|
||||
|
||||
local serverToData = {}
|
||||
|
||||
for _, proxy in ipairs(ARGV) do
|
||||
local players = call("SMEMBERS", "proxy:" .. proxy .. ":usersOnline")
|
||||
for _, player in ipairs(players) do
|
||||
local server = call("HGET", "player:" .. player, "server")
|
||||
if server then
|
||||
local sz = #serverToData
|
||||
serverToData[sz + 1] = server
|
||||
serverToData[sz + 2] = player
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return serverToData
|
||||
2
RedisBungee-API/src/main/resources/messages.yml
Normal file
2
RedisBungee-API/src/main/resources/messages.yml
Normal file
@@ -0,0 +1,2 @@
|
||||
logged-in-other-location: "§cYou logged in from another location!"
|
||||
already-logged-in: "§cYou are already logged in!"
|
||||
82
RedisBungee-Bungee/build.gradle.kts
Normal file
82
RedisBungee-Bungee/build.gradle.kts
Normal file
@@ -0,0 +1,82 @@
|
||||
plugins {
|
||||
`java-library`
|
||||
`maven-publish`
|
||||
id("com.github.johnrengelman.shadow") version "8.1.1"
|
||||
id("xyz.jpenilla.run-waterfall") version "2.0.0"
|
||||
}
|
||||
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots") } // bungeecord
|
||||
}
|
||||
val bungeecordApiVersion = "1.19-R0.1-SNAPSHOT"
|
||||
dependencies {
|
||||
api(project(":RedisBungee-API")) {
|
||||
exclude("com.google.guava", "guava")
|
||||
exclude("com.google.code.gson", "gson")
|
||||
}
|
||||
compileOnly("net.md-5:bungeecord-api:$bungeecordApiVersion")
|
||||
}
|
||||
|
||||
description = "RedisBungee Bungeecord implementation"
|
||||
|
||||
java {
|
||||
withJavadocJar()
|
||||
withSourcesJar()
|
||||
}
|
||||
|
||||
|
||||
tasks {
|
||||
withType<Javadoc> {
|
||||
dependsOn(project(":RedisBungee-API").getTasksByName("javadoc", false))
|
||||
val options = options as StandardJavadocDocletOptions
|
||||
options.use()
|
||||
options.isDocFilesSubDirs = true
|
||||
options.links(
|
||||
"https://ci.md-5.net/job/BungeeCord/ws/api/target/apidocs/", // bungeecord api
|
||||
)
|
||||
val apiDocs = File(rootProject.projectDir, "RedisBungee-API/build/docs/javadoc")
|
||||
options.linksOffline("https://ci.limework.net/RedisBungee/RedisBungee-API/build/docs/javadoc", apiDocs.path)
|
||||
}
|
||||
runWaterfall {
|
||||
waterfallVersion("1.19")
|
||||
}
|
||||
compileJava {
|
||||
options.encoding = Charsets.UTF_8.name()
|
||||
options.release.set(8)
|
||||
}
|
||||
javadoc {
|
||||
options.encoding = Charsets.UTF_8.name()
|
||||
}
|
||||
processResources {
|
||||
filteringCharset = Charsets.UTF_8.name()
|
||||
filesMatching("plugin.yml") {
|
||||
filter {
|
||||
it.replace("*{redisbungee.version}*", "$version", false)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
shadowJar {
|
||||
relocate("redis.clients.jedis", "com.imaginarycode.minecraft.redisbungee.internal.jedis")
|
||||
relocate("redis.clients.util", "com.imaginarycode.minecraft.redisbungee.internal.jedisutil")
|
||||
relocate("org.apache.commons.pool", "com.imaginarycode.minecraft.redisbungee.internal.commonspool")
|
||||
relocate("com.squareup.okhttp", "com.imaginarycode.minecraft.redisbungee.internal.okhttp")
|
||||
relocate("okio", "com.imaginarycode.minecraft.redisbungee.internal.okio")
|
||||
relocate("org.json", "com.imaginarycode.minecraft.redisbungee.internal.json")
|
||||
|
||||
// configurate shade
|
||||
relocate("ninja.leaping.configurate", "com.imaginarycode.minecraft.redisbungee.internal.configurate")
|
||||
relocate("org.yaml", "com.imaginarycode.minecraft.redisbungee.internal.yml")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
create<MavenPublication>("maven") {
|
||||
from(components["java"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>RedisBungee</artifactId>
|
||||
<groupId>com.imaginarycode.minecraft</groupId>
|
||||
<version>0.7.3-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>RedisBungee-Bungee</artifactId>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>bungeecord-repo</id>
|
||||
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>3.3.2</version>
|
||||
<configuration>
|
||||
<source>8</source>
|
||||
<reportOutputDirectory>../javadoc</reportOutputDirectory>
|
||||
<destDir>${project.name}</destDir>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.2.4</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals><goal>shade</goal></goals>
|
||||
<configuration>
|
||||
<relocations>
|
||||
<relocation>
|
||||
<pattern>redis.clients.jedis</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.jedis
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>redis.clients.util</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.jedisutil
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>org.apache.commons.pool</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.commonspool
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>com.squareup.okhttp</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.okhttp
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>okio</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.okio
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>com.google</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.google
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>org.json</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.json
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>org.checkerframework</pattern>
|
||||
<shadedPattern>com.imaginarycode.minecraft.redisbungee.internal.checkframework
|
||||
</shadedPattern>
|
||||
</relocation>
|
||||
</relocations>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.imaginarycode.minecraft</groupId>
|
||||
<artifactId>RedisBungee-API</artifactId>
|
||||
<version>${parent.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.md-5</groupId>
|
||||
<artifactId>bungeecord-api</artifactId>
|
||||
<version>1.17-R0.1-SNAPSHOT</version>
|
||||
<type>jar</type>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -1,15 +1,29 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PubSubMessageEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.DataManager;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.RedisBungeePlugin;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.AbstractDataManager;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
|
||||
import net.md_5.bungee.api.event.PostLoginEvent;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import net.md_5.bungee.event.EventHandler;
|
||||
|
||||
public class BungeeDataManager extends DataManager<ProxiedPlayer, PostLoginEvent, PlayerDisconnectEvent, PubSubMessageEvent> implements Listener {
|
||||
import java.util.UUID;
|
||||
|
||||
public class BungeeDataManager extends AbstractDataManager<ProxiedPlayer, PostLoginEvent, PlayerDisconnectEvent, PubSubMessageEvent> implements Listener {
|
||||
|
||||
public BungeeDataManager(RedisBungeePlugin<ProxiedPlayer> plugin) {
|
||||
super(plugin);
|
||||
@@ -32,4 +46,13 @@ public class BungeeDataManager extends DataManager<ProxiedPlayer, PostLoginEvent
|
||||
public void onPubSubMessage(PubSubMessageEvent event) {
|
||||
handlePubSubMessage(event.getChannel(), event.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleKick(UUID target, String message) {
|
||||
// check if the player is online on this proxy
|
||||
ProxiedPlayer player = plugin.getPlayer(target);
|
||||
if (player == null) return false;
|
||||
player.disconnect(TextComponent.fromLegacyText(message));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.player.PlayerUtils;
|
||||
import net.md_5.bungee.api.connection.PendingConnection;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
public class BungeePlayerUtils {
|
||||
|
||||
public static void createBungeePlayer(ProxiedPlayer player, UnifiedJedis unifiedJedis, boolean fireEvent) {
|
||||
String serverName = null;
|
||||
if (player.getServer() != null) {
|
||||
serverName = player.getServer().getInfo().getName();
|
||||
}
|
||||
PendingConnection pendingConnection = player.getPendingConnection();
|
||||
PlayerUtils.createPlayer(player.getUniqueId(), unifiedJedis, serverName, pendingConnection.getAddress().getAddress(), fireEvent);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.DataManager;
|
||||
import net.md_5.bungee.api.connection.PendingConnection;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import redis.clients.jedis.Pipeline;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class RBUtils {
|
||||
|
||||
private static final Gson gson = new Gson();
|
||||
|
||||
protected static void createPlayer(ProxiedPlayer player, Pipeline pipeline, boolean fireEvent) {
|
||||
createPlayer(player.getPendingConnection(), pipeline, fireEvent);
|
||||
if (player.getServer() != null)
|
||||
pipeline.hset("player:" + player.getUniqueId().toString(), "server", player.getServer().getInfo().getName());
|
||||
}
|
||||
|
||||
protected static void createPlayer(PendingConnection connection, Pipeline pipeline, boolean fireEvent) {
|
||||
Map<String, String> playerData = new HashMap<>(4);
|
||||
playerData.put("online", "0");
|
||||
playerData.put("ip", connection.getAddress().getAddress().getHostAddress());
|
||||
playerData.put("proxy", RedisBungeeAPI.getRedisBungeeApi().getServerId());
|
||||
|
||||
pipeline.sadd("proxy:" + RedisBungeeAPI.getRedisBungeeApi().getServerId() + ":usersOnline", connection.getUniqueId().toString());
|
||||
pipeline.hmset("player:" + connection.getUniqueId().toString(), playerData);
|
||||
|
||||
if (fireEvent) {
|
||||
pipeline.publish("redisbungee-data", gson.toJson(new DataManager.DataManagerMessage<>(
|
||||
connection.getUniqueId(), RedisBungeeAPI.getRedisBungeeApi().getServerId(), DataManager.DataManagerMessage.Action.JOIN,
|
||||
new DataManager.LoginPayload(connection.getAddress().getAddress()))));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.google.common.cache.Cache;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.config.ConfigLoader;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.config.RedisBungeeConfiguration;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPlayerChangedServerNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPlayerJoinedNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPlayerLeftNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPubSubMessageEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.tasks.*;
|
||||
import com.imaginarycode.minecraft.redisbungee.commands.RedisBungeeCommands;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PlayerChangedServerNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PlayerJoinedNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PlayerLeftNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PubSubMessageEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.*;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.summoners.Summoner;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeeMode;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.uuid.NameFetcher;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.uuid.UUIDFetcher;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.uuid.UUIDTranslator;
|
||||
import com.squareup.okhttp.Dispatcher;
|
||||
import com.squareup.okhttp.OkHttpClient;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.plugin.Event;
|
||||
import net.md_5.bungee.api.plugin.Plugin;
|
||||
import redis.clients.jedis.*;
|
||||
|
||||
import java.io.*;
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.InetAddress;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.logging.Level;
|
||||
|
||||
|
||||
public class RedisBungee extends Plugin implements RedisBungeePlugin<ProxiedPlayer>, ConfigLoader {
|
||||
|
||||
private static RedisBungeeAPI apiStatic;
|
||||
|
||||
private AbstractRedisBungeeAPI api;
|
||||
private RedisBungeeMode redisBungeeMode;
|
||||
private PubSubListener psl = null;
|
||||
private Summoner<?> summoner;
|
||||
private UUIDTranslator uuidTranslator;
|
||||
private RedisBungeeConfiguration configuration;
|
||||
private BungeeDataManager dataManager;
|
||||
private OkHttpClient httpClient;
|
||||
private volatile List<String> proxiesIds;
|
||||
private final AtomicInteger globalPlayerCount = new AtomicInteger();
|
||||
private Future<?> integrityCheck;
|
||||
private Future<?> heartbeatTask;
|
||||
private static final Object SERVER_TO_PLAYERS_KEY = new Object();
|
||||
private final Cache<Object, Multimap<String, UUID>> serverToPlayersCache = CacheBuilder.newBuilder()
|
||||
.expireAfterWrite(5, TimeUnit.SECONDS)
|
||||
.build();
|
||||
|
||||
|
||||
@Override
|
||||
public RedisBungeeConfiguration getConfiguration() {
|
||||
return this.configuration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCount() {
|
||||
return this.globalPlayerCount.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> getLocalPlayersAsUuidStrings() {
|
||||
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
|
||||
for (ProxiedPlayer player : getProxy().getPlayers()) {
|
||||
builder.add(player.getUniqueId().toString());
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractDataManager<ProxiedPlayer, ?, ?, ?> getDataManager() {
|
||||
return this.dataManager;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public AbstractRedisBungeeAPI getAbstractRedisBungeeApi() {
|
||||
return this.api;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUIDTranslator getUuidTranslator() {
|
||||
return this.uuidTranslator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Multimap<String, UUID> serverToPlayersCache() {
|
||||
try {
|
||||
return this.serverToPlayersCache.get(SERVER_TO_PLAYERS_KEY, this::serversToPlayers);
|
||||
} catch (ExecutionException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getProxiesIds() {
|
||||
return proxiesIds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PubSubListener getPubSubListener() {
|
||||
return this.psl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void executeAsync(Runnable runnable) {
|
||||
this.getProxy().getScheduler().runAsync(this, runnable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void executeAsyncAfter(Runnable runnable, TimeUnit timeUnit, int time) {
|
||||
this.getProxy().getScheduler().schedule(this, runnable, time, timeUnit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fireEvent(Object event) {
|
||||
this.getProxy().getPluginManager().callEvent((Event) event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOnlineMode() {
|
||||
return this.getProxy().getConfig().isOnlineMode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void logInfo(String msg) {
|
||||
this.getLogger().info(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void logWarn(String msg) {
|
||||
this.getLogger().warning(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void logFatal(String msg) {
|
||||
this.getLogger().severe(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProxiedPlayer getPlayer(UUID uuid) {
|
||||
return this.getProxy().getPlayer(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProxiedPlayer getPlayer(String name) {
|
||||
return this.getProxy().getPlayer(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getPlayerUUID(String player) {
|
||||
return this.getProxy().getPlayer(player).getUniqueId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlayerName(UUID player) {
|
||||
return this.getProxy().getPlayer(player).getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlayerServerName(ProxiedPlayer player) {
|
||||
return player.getServer().getInfo().getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayerOnAServer(ProxiedPlayer player) {
|
||||
return player.getServer() != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InetAddress getPlayerIp(ProxiedPlayer player) {
|
||||
return player.getAddress().getAddress();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void initialize() {
|
||||
logInfo("Initializing RedisBungee.....");
|
||||
ThreadFactory factory = ((ThreadPoolExecutor) getExecutorService()).getThreadFactory();
|
||||
ScheduledExecutorService service = Executors.newScheduledThreadPool(24, factory);
|
||||
try {
|
||||
Field field = Plugin.class.getDeclaredField("service");
|
||||
field.setAccessible(true);
|
||||
ExecutorService builtinService = (ExecutorService) field.get(this);
|
||||
field.set(this, service);
|
||||
builtinService.shutdownNow();
|
||||
} catch (IllegalAccessException | NoSuchFieldException e) {
|
||||
getLogger().log(Level.WARNING, "Can't replace BungeeCord thread pool with our own");
|
||||
getLogger().log(Level.INFO, "skipping replacement.....");
|
||||
}
|
||||
try {
|
||||
loadConfig(this, getDataFolder());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Unable to load/save config", e);
|
||||
}
|
||||
// init the api class
|
||||
this.api = new RedisBungeeAPI(this);
|
||||
apiStatic = (RedisBungeeAPI) this.api;
|
||||
// init the http lib
|
||||
httpClient = new OkHttpClient();
|
||||
Dispatcher dispatcher = new Dispatcher(getExecutorService());
|
||||
httpClient.setDispatcher(dispatcher);
|
||||
//NameFetcher.setHttpClient(httpClient);
|
||||
UUIDFetcher.setHttpClient(httpClient);
|
||||
InitialUtils.checkRedisVersion(this);
|
||||
// check if this proxy is recovering from a crash and start heart the beat.
|
||||
InitialUtils.checkIfRecovering(this, getDataFolder().toPath());
|
||||
updateProxiesIds();
|
||||
uuidTranslator = new UUIDTranslator(this);
|
||||
heartbeatTask = service.scheduleAtFixedRate(new HeartbeatTask(this, this.globalPlayerCount), 0, HeartbeatTask.INTERVAL, HeartbeatTask.REPEAT_INTERVAL_TIME_UNIT);
|
||||
dataManager = new BungeeDataManager(this);
|
||||
getProxy().getPluginManager().registerListener(this, new RedisBungeeBungeeListener(this, configuration.getExemptAddresses()));
|
||||
getProxy().getPluginManager().registerListener(this, dataManager);
|
||||
psl = new PubSubListener(this);
|
||||
getProxy().getScheduler().runAsync(this, psl);
|
||||
|
||||
IntegrityCheckTask integrityCheckTask = new IntegrityCheckTask(this) {
|
||||
@Override
|
||||
public void handlePlatformPlayer(String player, UnifiedJedis unifiedJedis) {
|
||||
ProxiedPlayer proxiedPlayer = ProxyServer.getInstance().getPlayer(UUID.fromString(player));
|
||||
if (proxiedPlayer == null)
|
||||
return; // We'll deal with it later.
|
||||
|
||||
BungeePlayerUtils.createBungeePlayer(proxiedPlayer, unifiedJedis, false);
|
||||
}
|
||||
};
|
||||
|
||||
integrityCheck = service.scheduleAtFixedRate(integrityCheckTask::execute, 0, IntegrityCheckTask.INTERVAL, IntegrityCheckTask.TIMEUNIT);
|
||||
|
||||
// register plugin messages channel.
|
||||
getProxy().registerChannel("legacy:redisbungee");
|
||||
getProxy().registerChannel("RedisBungee");
|
||||
if (configuration.doRegisterLegacyCommands()) {
|
||||
// register commands
|
||||
if (configuration.doOverrideBungeeCommands()) {
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.GlistCommand(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.FindCommand(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.LastSeenCommand(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.IpCommand(this));
|
||||
}
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.SendToAll(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.ServerId(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.ServerIds(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.PlayerProxyCommand(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.PlistCommand(this));
|
||||
}
|
||||
logInfo("RedisBungee initialized successfully ");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
logInfo("Turning off redis connections.....");
|
||||
// Poison the PubSub listener
|
||||
if (psl != null) {
|
||||
psl.poison();
|
||||
}
|
||||
if (integrityCheck != null) {
|
||||
integrityCheck.cancel(true);
|
||||
}
|
||||
if (heartbeatTask != null) {
|
||||
heartbeatTask.cancel(true);
|
||||
}
|
||||
getProxy().getPluginManager().unregisterListeners(this);
|
||||
ShutdownUtils.shutdownCleanup(this);
|
||||
try {
|
||||
this.summoner.close();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
logInfo("RedisBungee shutdown");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Summoner<?> getSummoner() {
|
||||
return this.summoner;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RedisBungeeMode getRedisBungeeMode() {
|
||||
return this.redisBungeeMode;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void updateProxiesIds() {
|
||||
proxiesIds = getCurrentProxiesIds(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
initialize();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
stop();
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlayerChangedServerNetworkEvent createPlayerChangedServerNetworkEvent(UUID uuid, String previousServer, String server) {
|
||||
return new PlayerChangedServerNetworkEvent(uuid, previousServer, server);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlayerJoinedNetworkEvent createPlayerJoinedNetworkEvent(UUID uuid) {
|
||||
return new PlayerJoinedNetworkEvent(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlayerLeftNetworkEvent createPlayerLeftNetworkEvent(UUID uuid) {
|
||||
return new PlayerLeftNetworkEvent(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPubSubMessageEvent createPubSubEvent(String channel, String message) {
|
||||
return new PubSubMessageEvent(channel, message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConfigLoad(RedisBungeeConfiguration configuration, Summoner<?> summoner, RedisBungeeMode mode) {
|
||||
this.configuration = configuration;
|
||||
this.redisBungeeMode = mode;
|
||||
this.summoner = summoner;
|
||||
}
|
||||
|
||||
/**
|
||||
* This returns an instance of {@link RedisBungeeAPI}
|
||||
*
|
||||
* @deprecated Please use {@link RedisBungeeAPI#getRedisBungeeApi()} this class intended to for old plugins that no longer updated.
|
||||
*
|
||||
* @return the {@link AbstractRedisBungeeAPI} object instance.
|
||||
*/
|
||||
@Deprecated
|
||||
public static RedisBungeeAPI getApi() {
|
||||
return apiStatic;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public JedisPool getPool() {
|
||||
return api.getJedisPool();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import net.md_5.bungee.api.config.ServerInfo;
|
||||
import net.md_5.bungee.api.plugin.Plugin;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* This platform class exposes some internal RedisBungee functions. You obtain an instance of this object by invoking {@link RedisBungeeAPI#getRedisBungeeApi()}
|
||||
* or somehow you got the Plugin instance by you can call the api using {@link RedisBungeePlugin#getAbstractRedisBungeeApi()}.
|
||||
*
|
||||
* @author tuxed
|
||||
* @since 0.2.3 | updated 0.8.0
|
||||
*/
|
||||
public class RedisBungeeAPI extends AbstractRedisBungeeAPI {
|
||||
|
||||
private static RedisBungeeAPI redisBungeeApi;
|
||||
|
||||
public RedisBungeeAPI(RedisBungeePlugin<?> plugin) {
|
||||
super(plugin);
|
||||
if (redisBungeeApi == null) {
|
||||
redisBungeeApi = this;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the server where the specified player is playing. This function also deals with the case of local players
|
||||
* as well, and will return local information on them.
|
||||
*
|
||||
* @param player a player uuid
|
||||
* @return {@link ServerInfo} Can be null if proxy can't find it.
|
||||
* @see #getServerNameFor(UUID)
|
||||
*/
|
||||
@Nullable
|
||||
public final ServerInfo getServerFor(@NonNull UUID player) {
|
||||
String serverName = this.getServerNameFor(player);
|
||||
if (serverName == null) return null;
|
||||
return ((Plugin) this.plugin).getProxy().getServerInfo(serverName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Api instance
|
||||
*
|
||||
* @return the API instance.
|
||||
* @since 0.6.5
|
||||
*/
|
||||
public static RedisBungeeAPI getRedisBungeeApi() {
|
||||
return redisBungeeApi;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,13 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
@@ -6,14 +16,14 @@ import com.google.common.collect.Multimap;
|
||||
import com.google.common.io.ByteArrayDataInput;
|
||||
import com.google.common.io.ByteArrayDataOutput;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.AbstractRedisBungeeListener;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.DataManager;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.RedisBungeePlugin;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.AbstractRedisBungeeListener;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.config.RedisBungeeConfiguration;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.player.PlayerUtils;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.tasks.RedisTask;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.payload.PayloadUtils;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PubSubMessageEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.RedisUtil;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.util.RedisCallable;
|
||||
import net.md_5.bungee.api.AbstractReconnectHandler;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import net.md_5.bungee.api.config.ServerInfo;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.connection.Server;
|
||||
@@ -21,51 +31,44 @@ import net.md_5.bungee.api.event.*;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import net.md_5.bungee.api.plugin.Plugin;
|
||||
import net.md_5.bungee.event.EventHandler;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.Pipeline;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.*;
|
||||
|
||||
public class RedisBungeeListener extends AbstractRedisBungeeListener<LoginEvent, PostLoginEvent, PlayerDisconnectEvent, ServerConnectedEvent, ProxyPingEvent, PluginMessageEvent, PubSubMessageEvent> implements Listener {
|
||||
import static com.imaginarycode.minecraft.redisbungee.api.util.serialize.Serializations.serializeMultimap;
|
||||
import static com.imaginarycode.minecraft.redisbungee.api.util.serialize.Serializations.serializeMultiset;
|
||||
import static net.md_5.bungee.event.EventPriority.HIGHEST;
|
||||
|
||||
public class RedisBungeeBungeeListener extends AbstractRedisBungeeListener<LoginEvent, PostLoginEvent, PlayerDisconnectEvent, ServerConnectedEvent, ProxyPingEvent, PluginMessageEvent, PubSubMessageEvent> implements Listener {
|
||||
|
||||
|
||||
public RedisBungeeListener(RedisBungeePlugin<?> plugin, List<InetAddress> exemptAddresses) {
|
||||
public RedisBungeeBungeeListener(RedisBungeePlugin<?> plugin, List<InetAddress> exemptAddresses) {
|
||||
super(plugin, exemptAddresses);
|
||||
}
|
||||
|
||||
@Override
|
||||
@EventHandler
|
||||
@EventHandler(priority = HIGHEST)
|
||||
public void onLogin(LoginEvent event) {
|
||||
event.registerIntent((Plugin) plugin);
|
||||
plugin.executeAsync(new RedisCallable<Void>(plugin) {
|
||||
plugin.executeAsync(new RedisTask<Void>(plugin) {
|
||||
@Override
|
||||
protected Void call(Jedis jedis) {
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
try {
|
||||
if (event.isCancelled()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// We make sure they aren't trying to use an existing player's name.
|
||||
// This is problematic for online-mode servers as they always disconnect old clients.
|
||||
if (plugin.isOnlineMode()) {
|
||||
ProxiedPlayer player = (ProxiedPlayer) plugin.getPlayer(event.getConnection().getName());
|
||||
|
||||
if (player != null) {
|
||||
event.setCancelled(true);
|
||||
// TODO: Make it accept a BaseComponent[] like everything else.
|
||||
event.setCancelReason(ONLINE_MODE_RECONNECT);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
for (String s : plugin.getServerIds()) {
|
||||
if (jedis.sismember("proxy:" + s + ":usersOnline", event.getConnection().getUniqueId().toString())) {
|
||||
event.setCancelled(true);
|
||||
// TODO: Make it accept a BaseComponent[] like everything else.
|
||||
event.setCancelReason(ALREADY_LOGGED_IN);
|
||||
return null;
|
||||
if (plugin.getConfiguration().restoreOldKickBehavior()) {
|
||||
for (String s : plugin.getProxiesIds()) {
|
||||
if (unifiedJedis.sismember("proxy:" + s + ":usersOnline", event.getConnection().getUniqueId().toString())) {
|
||||
event.setCancelled(true);
|
||||
event.setCancelReason(plugin.getConfiguration().getMessages().get(RedisBungeeConfiguration.MessageType.ALREADY_LOGGED_IN));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} else if (api.isPlayerOnline(event.getConnection().getUniqueId())) {
|
||||
PlayerUtils.setKickedOtherLocation(event.getConnection().getUniqueId().toString(), unifiedJedis);
|
||||
api.kickPlayer(event.getConnection().getUniqueId(), plugin.getConfiguration().getMessages().get(RedisBungeeConfiguration.MessageType.LOGGED_IN_OTHER_LOCATION));
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
@@ -78,21 +81,11 @@ public class RedisBungeeListener extends AbstractRedisBungeeListener<LoginEvent,
|
||||
@Override
|
||||
@EventHandler
|
||||
public void onPostLogin(PostLoginEvent event) {
|
||||
plugin.executeAsync(new RedisCallable<Void>(plugin) {
|
||||
plugin.executeAsync(new RedisTask<Void>(plugin) {
|
||||
@Override
|
||||
protected Void call(Jedis jedis) {
|
||||
// this code was moved out from login event due being async..
|
||||
// and it can be cancelled but it will show as false in redis-bungee
|
||||
// which will register the player into the redis database.
|
||||
Pipeline pipeline = jedis.pipelined();
|
||||
plugin.getUuidTranslator().persistInfo(event.getPlayer().getName(), event.getPlayer().getUniqueId(), pipeline);
|
||||
RBUtils.createPlayer(event.getPlayer(), pipeline, false);
|
||||
pipeline.sync();
|
||||
// the end of moved code.
|
||||
|
||||
jedis.publish("redisbungee-data", gson.toJson(new DataManager.DataManagerMessage(
|
||||
event.getPlayer().getUniqueId(), plugin.getApi().getServerId(), DataManager.DataManagerMessage.Action.JOIN,
|
||||
new DataManager.LoginPayload(event.getPlayer().getAddress().getAddress()))));
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
plugin.getUuidTranslator().persistInfo(event.getPlayer().getName(), event.getPlayer().getUniqueId(), unifiedJedis);
|
||||
BungeePlayerUtils.createBungeePlayer(event.getPlayer(), unifiedJedis, true);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
@@ -101,12 +94,10 @@ public class RedisBungeeListener extends AbstractRedisBungeeListener<LoginEvent,
|
||||
@Override
|
||||
@EventHandler
|
||||
public void onPlayerDisconnect(PlayerDisconnectEvent event) {
|
||||
plugin.executeAsync(new RedisCallable<Void>(plugin) {
|
||||
plugin.executeAsync(new RedisTask<Void>(plugin) {
|
||||
@Override
|
||||
protected Void call(Jedis jedis) {
|
||||
Pipeline pipeline = jedis.pipelined();
|
||||
RedisUtil.cleanUpPlayer(event.getPlayer().getUniqueId().toString(), pipeline);
|
||||
pipeline.sync();
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
PlayerUtils.cleanUpPlayer(event.getPlayer().getUniqueId().toString(), unifiedJedis, true);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
@@ -116,14 +107,13 @@ public class RedisBungeeListener extends AbstractRedisBungeeListener<LoginEvent,
|
||||
@Override
|
||||
@EventHandler
|
||||
public void onServerChange(ServerConnectedEvent event) {
|
||||
final String currentServer = event.getPlayer().getServer() == null ? null : event.getPlayer().getServer().getInfo().getName();
|
||||
plugin.executeAsync(new RedisCallable<Void>(plugin) {
|
||||
final String currentServer = event.getServer().getInfo().getName();
|
||||
final String oldServer = event.getPlayer().getServer() == null ? null : event.getPlayer().getServer().getInfo().getName();
|
||||
plugin.executeAsync(new RedisTask<Void>(plugin) {
|
||||
@Override
|
||||
protected Void call(Jedis jedis) {
|
||||
jedis.hset("player:" + event.getPlayer().getUniqueId().toString(), "server", event.getServer().getInfo().getName());
|
||||
jedis.publish("redisbungee-data", gson.toJson(new DataManager.DataManagerMessage(
|
||||
event.getPlayer().getUniqueId(), plugin.getApi().getServerId(), DataManager.DataManagerMessage.Action.SERVER_CHANGE,
|
||||
new DataManager.ServerChangePayload(event.getServer().getInfo().getName(), currentServer))));
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
unifiedJedis.hset("player:" + event.getPlayer().getUniqueId().toString(), "server", event.getServer().getInfo().getName());
|
||||
PayloadUtils.playerServerChangePayload(event.getPlayer().getUniqueId(), unifiedJedis, currentServer, oldServer);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
@@ -166,8 +156,9 @@ public class RedisBungeeListener extends AbstractRedisBungeeListener<LoginEvent,
|
||||
out.writeUTF("ALL");
|
||||
original = plugin.getPlayers();
|
||||
} else {
|
||||
out.writeUTF(type);
|
||||
try {
|
||||
original = plugin.getApi().getPlayersOnServer(type);
|
||||
original = plugin.getAbstractRedisBungeeApi().getPlayersOnServer(type);
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
@@ -185,7 +176,7 @@ public class RedisBungeeListener extends AbstractRedisBungeeListener<LoginEvent,
|
||||
} else {
|
||||
out.writeUTF(type);
|
||||
try {
|
||||
out.writeInt(plugin.getApi().getPlayersOnServer(type).size());
|
||||
out.writeInt(plugin.getAbstractRedisBungeeApi().getPlayersOnServer(type).size());
|
||||
} catch (IllegalArgumentException e) {
|
||||
out.writeInt(0);
|
||||
}
|
||||
@@ -195,12 +186,12 @@ public class RedisBungeeListener extends AbstractRedisBungeeListener<LoginEvent,
|
||||
String user = in.readUTF();
|
||||
out.writeUTF("LastOnline");
|
||||
out.writeUTF(user);
|
||||
out.writeLong(plugin.getApi().getLastOnline(plugin.getUuidTranslator().getTranslatedUuid(user, true)));
|
||||
out.writeLong(plugin.getAbstractRedisBungeeApi().getLastOnline(Objects.requireNonNull(plugin.getUuidTranslator().getTranslatedUuid(user, true))));
|
||||
break;
|
||||
case "ServerPlayers":
|
||||
String type1 = in.readUTF();
|
||||
out.writeUTF("ServerPlayers");
|
||||
Multimap<String, UUID> multimap = plugin.getApi().getServerToPlayers();
|
||||
Multimap<String, UUID> multimap = plugin.getAbstractRedisBungeeApi().getServerToPlayers();
|
||||
|
||||
boolean includesUsers;
|
||||
|
||||
@@ -230,13 +221,13 @@ public class RedisBungeeListener extends AbstractRedisBungeeListener<LoginEvent,
|
||||
break;
|
||||
case "Proxy":
|
||||
out.writeUTF("Proxy");
|
||||
out.writeUTF(plugin.getConfiguration().getServerId());
|
||||
out.writeUTF(plugin.getConfiguration().getProxyId());
|
||||
break;
|
||||
case "PlayerProxy":
|
||||
String username = in.readUTF();
|
||||
out.writeUTF("PlayerProxy");
|
||||
out.writeUTF(username);
|
||||
out.writeUTF(plugin.getApi().getProxy(plugin.getUuidTranslator().getTranslatedUuid(username, true)));
|
||||
out.writeUTF(plugin.getAbstractRedisBungeeApi().getProxy(Objects.requireNonNull(plugin.getUuidTranslator().getTranslatedUuid(username, true))));
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
@@ -250,7 +241,7 @@ public class RedisBungeeListener extends AbstractRedisBungeeListener<LoginEvent,
|
||||
@Override
|
||||
@EventHandler
|
||||
public void onPubSubMessage(PubSubMessageEvent event) {
|
||||
if (event.getChannel().equals("redisbungee-allservers") || event.getChannel().equals("redisbungee-" + plugin.getApi().getServerId())) {
|
||||
if (event.getChannel().equals("redisbungee-allservers") || event.getChannel().equals("redisbungee-" + plugin.getAbstractRedisBungeeApi().getProxyId())) {
|
||||
String message = event.getMessage();
|
||||
if (message.startsWith("/"))
|
||||
message = message.substring(1);
|
||||
@@ -1,640 +0,0 @@
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.google.common.cache.Cache;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMultimap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.google.gson.Gson;
|
||||
import com.imaginarycode.minecraft.redisbungee.commands.RedisBungeeCommands;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PlayerChangedServerNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PlayerJoinedNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PubSubMessageEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.*;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.util.IOUtil;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.util.LuaManager;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.util.uuid.NameFetcher;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.util.uuid.UUIDFetcher;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.util.uuid.UUIDTranslator;
|
||||
import com.squareup.okhttp.Dispatcher;
|
||||
import com.squareup.okhttp.OkHttpClient;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.plugin.Event;
|
||||
import net.md_5.bungee.api.plugin.Plugin;
|
||||
import net.md_5.bungee.config.Configuration;
|
||||
import net.md_5.bungee.config.ConfigurationProvider;
|
||||
import net.md_5.bungee.config.YamlConfiguration;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.JedisPoolConfig;
|
||||
import redis.clients.jedis.Pipeline;
|
||||
import redis.clients.jedis.exceptions.JedisConnectionException;
|
||||
|
||||
import java.io.*;
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.InetAddress;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
|
||||
public class RedisBungeeBungeePlugin extends Plugin implements RedisBungeePlugin<ProxiedPlayer> {
|
||||
|
||||
private static final Gson gson = new Gson();
|
||||
private RedisBungeeAPI api;
|
||||
private PubSubListener psl = null;
|
||||
private JedisPool jedisPool;
|
||||
private UUIDTranslator uuidTranslator;
|
||||
private RedisBungeeConfiguration configuration;
|
||||
private BungeeDataManager dataManager;
|
||||
private OkHttpClient httpClient;
|
||||
private volatile List<String> serverIds;
|
||||
private final AtomicInteger nagAboutServers = new AtomicInteger();
|
||||
private final AtomicInteger globalPlayerCount = new AtomicInteger();
|
||||
private Future<?> integrityCheck;
|
||||
private Future<?> heartbeatTask;
|
||||
private LuaManager.Script serverToPlayersScript;
|
||||
private LuaManager.Script getPlayerCountScript;
|
||||
|
||||
private static final Object SERVER_TO_PLAYERS_KEY = new Object();
|
||||
private final Cache<Object, Multimap<String, UUID>> serverToPlayersCache = CacheBuilder.newBuilder()
|
||||
.expireAfterWrite(5, TimeUnit.SECONDS)
|
||||
.build();
|
||||
|
||||
|
||||
@Override
|
||||
public RedisBungeeConfiguration getConfiguration() {
|
||||
return this.configuration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCount() {
|
||||
return this.globalPlayerCount.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCurrentCount() {
|
||||
Long count = (Long) getPlayerCountScript.eval(ImmutableList.<String>of(), ImmutableList.<String>of());
|
||||
return count.intValue();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> getLocalPlayersAsUuidStrings() {
|
||||
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
|
||||
for (ProxiedPlayer player : getProxy().getPlayers()) {
|
||||
builder.add(player.getUniqueId().toString());
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataManager<ProxiedPlayer, ?, ?, ?> getDataManager() {
|
||||
return this.dataManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<UUID> getPlayers() {
|
||||
ImmutableSet.Builder<UUID> setBuilder = ImmutableSet.builder();
|
||||
if (isJedisAvailable()) {
|
||||
try (Jedis rsc = requestJedis()) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
for (String i : getServerIds()) {
|
||||
keys.add("proxy:" + i + ":usersOnline");
|
||||
}
|
||||
if (!keys.isEmpty()) {
|
||||
Set<String> users = rsc.sunion(keys.toArray(new String[keys.size()]));
|
||||
if (users != null && !users.isEmpty()) {
|
||||
for (String user : users) {
|
||||
try {
|
||||
setBuilder = setBuilder.add(UUID.fromString(user));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (JedisConnectionException e) {
|
||||
// Redis server has disappeared!
|
||||
getLogger().log(Level.SEVERE, "Unable to get connection from pool - did your Redis server go away?", e);
|
||||
throw new RuntimeException("Unable to get all players online", e);
|
||||
}
|
||||
}
|
||||
return setBuilder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Jedis requestJedis() {
|
||||
return this.jedisPool.getResource();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isJedisAvailable() {
|
||||
return !jedisPool.isClosed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public JedisPool getJedisPool() {
|
||||
return this.jedisPool;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RedisBungeeAPI getApi() {
|
||||
return this.api;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUIDTranslator getUuidTranslator() {
|
||||
return this.uuidTranslator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Multimap<String, UUID> serversToPlayers() {
|
||||
try {
|
||||
return serverToPlayersCache.get(SERVER_TO_PLAYERS_KEY, new Callable<Multimap<String, UUID>>() {
|
||||
@Override
|
||||
public Multimap<String, UUID> call() throws Exception {
|
||||
Collection<String> data = (Collection<String>) serverToPlayersScript.eval(ImmutableList.<String>of(), getServerIds());
|
||||
ImmutableMultimap.Builder<String, UUID> builder = ImmutableMultimap.builder();
|
||||
String key = null;
|
||||
for (String s : data) {
|
||||
if (key == null) {
|
||||
key = s;
|
||||
continue;
|
||||
}
|
||||
|
||||
builder.put(key, UUID.fromString(s));
|
||||
key = null;
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
});
|
||||
} catch (ExecutionException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<UUID> getPlayersOnProxy(String proxyId) {
|
||||
checkArgument(getServerIds().contains(proxyId), proxyId + " is not a valid proxy ID");
|
||||
try (Jedis jedis = requestJedis()) {
|
||||
Set<String> users = jedis.smembers("proxy:" + proxyId + ":usersOnline");
|
||||
ImmutableSet.Builder<UUID> builder = ImmutableSet.builder();
|
||||
for (String user : users) {
|
||||
builder.add(UUID.fromString(user));
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendProxyCommand(String serverId, String command) {
|
||||
checkArgument(getServerIds().contains(serverId) || serverId.equals("allservers"), "proxyId is invalid");
|
||||
sendChannelMessage("redisbungee-" + serverId, command);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getServerIds() {
|
||||
return serverIds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getCurrentServerIds(boolean nag, boolean lagged) {
|
||||
try (Jedis jedis = requestJedis()) {
|
||||
long time = getRedisTime(jedis.time());
|
||||
int nagTime = 0;
|
||||
if (nag) {
|
||||
nagTime = nagAboutServers.decrementAndGet();
|
||||
if (nagTime <= 0) {
|
||||
nagAboutServers.set(10);
|
||||
}
|
||||
}
|
||||
ImmutableList.Builder<String> servers = ImmutableList.builder();
|
||||
Map<String, String> heartbeats = jedis.hgetAll("heartbeats");
|
||||
for (Map.Entry<String, String> entry : heartbeats.entrySet()) {
|
||||
try {
|
||||
long stamp = Long.parseLong(entry.getValue());
|
||||
if (lagged ? time >= stamp + 30 : time <= stamp + 30)
|
||||
servers.add(entry.getKey());
|
||||
else if (nag && nagTime <= 0) {
|
||||
getLogger().warning(entry.getKey() + " is " + (time - stamp) + " seconds behind! (Time not synchronized or server down?) and was removed from heartbeat.");
|
||||
jedis.hdel("heartbeats", entry.getKey());
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
return servers.build();
|
||||
} catch (JedisConnectionException e) {
|
||||
getLogger().log(Level.SEVERE, "Unable to fetch server IDs", e);
|
||||
return Collections.singletonList(configuration.getServerId());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PubSubListener getPubSubListener() {
|
||||
return this.psl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendChannelMessage(String channel, String message) {
|
||||
try (Jedis jedis = requestJedis()) {
|
||||
jedis.publish(channel, message);
|
||||
} catch (JedisConnectionException e) {
|
||||
// Redis server has disappeared!
|
||||
getLogger().log(Level.SEVERE, "Unable to get connection from pool - did your Redis server go away?", e);
|
||||
throw new RuntimeException("Unable to publish channel message", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void executeAsync(Runnable runnable) {
|
||||
this.getProxy().getScheduler().runAsync(this, runnable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void executeAsyncAfter(Runnable runnable, TimeUnit timeUnit, int time) {
|
||||
this.getProxy().getScheduler().schedule(this, runnable, time, timeUnit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void callEvent(Object event) {
|
||||
this.getProxy().getPluginManager().callEvent((Event) event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOnlineMode() {
|
||||
return this.getProxy().getConfig().isOnlineMode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void logInfo(String msg) {
|
||||
this.getLogger().info(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void logWarn(String msg) {
|
||||
this.getLogger().warning(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void logFatal(String msg) {
|
||||
this.getLogger().severe(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProxiedPlayer getPlayer(UUID uuid) {
|
||||
return this.getProxy().getPlayer(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProxiedPlayer getPlayer(String name) {
|
||||
return this.getProxy().getPlayer(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getPlayerUUID(String player) {
|
||||
return this.getProxy().getPlayer(player).getUniqueId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlayerName(UUID player) {
|
||||
return this.getProxy().getPlayer(player).getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlayerServerName(ProxiedPlayer player) {
|
||||
return player.getServer().getInfo().getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayerOnAServer(ProxiedPlayer player) {
|
||||
return player.getServer() != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InetAddress getPlayerIp(ProxiedPlayer player) {
|
||||
return player.getAddress().getAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendProxyCommand(String cmd) {
|
||||
checkArgument(getServerIds().contains(this.configuration.getServerId()) || this.configuration.getServerId().equals("allservers"), "proxyId is invalid");
|
||||
sendChannelMessage("redisbungee-" + this.configuration.getServerId(), cmd);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getRedisTime(List<String> timeRes) {
|
||||
return Long.parseLong(timeRes.get(0));
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void enable() {
|
||||
ThreadFactory factory = ((ThreadPoolExecutor) getExecutorService()).getThreadFactory();
|
||||
ScheduledExecutorService service = Executors.newScheduledThreadPool(24, factory);
|
||||
try {
|
||||
Field field = Plugin.class.getDeclaredField("service");
|
||||
field.setAccessible(true);
|
||||
ExecutorService builtinService = (ExecutorService) field.get(this);
|
||||
field.set(this, service);
|
||||
builtinService.shutdownNow();
|
||||
} catch (IllegalAccessException | NoSuchFieldException e) {
|
||||
getLogger().log(Level.WARNING, "Can't replace BungeeCord thread pool with our own");
|
||||
getLogger().log(Level.INFO, "skipping replacement.....");
|
||||
}
|
||||
try {
|
||||
loadConfig();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Unable to load/save config", e);
|
||||
} catch (JedisConnectionException e) {
|
||||
throw new RuntimeException("Unable to connect to your Redis server!", e);
|
||||
}
|
||||
this.api = new RedisBungeeAPI(this);
|
||||
// call old plugin class to support old plugins
|
||||
new RedisBungee(api);
|
||||
if (isJedisAvailable()) {
|
||||
try (Jedis tmpRsc = requestJedis()) {
|
||||
// This is more portable than INFO <section>
|
||||
String info = tmpRsc.info();
|
||||
for (String s : info.split("\r\n")) {
|
||||
if (s.startsWith("redis_version:")) {
|
||||
String version = s.split(":")[1];
|
||||
getLogger().info(version + " <- redis version");
|
||||
if (!RedisUtil.isRedisVersionRight(version)) {
|
||||
getLogger().warning("Your version of Redis (" + version + ") is not at least version 6.0 RedisBungee requires a newer version of Redis.");
|
||||
throw new RuntimeException("Unsupported Redis version detected");
|
||||
} else {
|
||||
LuaManager manager = new LuaManager(this);
|
||||
serverToPlayersScript = manager.createScript(IOUtil.readInputStreamAsString(getResourceAsStream("lua/server_to_players.lua")));
|
||||
getPlayerCountScript = manager.createScript(IOUtil.readInputStreamAsString(getResourceAsStream("lua/get_player_count.lua")));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
tmpRsc.hset("heartbeats", configuration.getServerId(), tmpRsc.time().get(0));
|
||||
|
||||
long uuidCacheSize = tmpRsc.hlen("uuid-cache");
|
||||
if (uuidCacheSize > 750000) {
|
||||
getLogger().info("Looks like you have a really big UUID cache! Run https://www.spigotmc.org/resources/redisbungeecleaner.8505/ as soon as possible.");
|
||||
}
|
||||
}
|
||||
serverIds = getCurrentServerIds(true, false);
|
||||
uuidTranslator = new UUIDTranslator(this);
|
||||
heartbeatTask = service.scheduleAtFixedRate(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try (Jedis rsc = requestJedis()) {
|
||||
long redisTime = getRedisTime(rsc.time());
|
||||
rsc.hset("heartbeats", configuration.getServerId(), String.valueOf(redisTime));
|
||||
} catch (JedisConnectionException e) {
|
||||
// Redis server has disappeared!
|
||||
getLogger().log(Level.SEVERE, "Unable to update heartbeat - did your Redis server go away?", e);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
serverIds = getCurrentServerIds(true, false);
|
||||
globalPlayerCount.set(getCurrentCount());
|
||||
} catch (Throwable e) {
|
||||
getLogger().log(Level.SEVERE, "Unable to update data - did your Redis server go away?", e);
|
||||
}
|
||||
}
|
||||
}, 0, 3, TimeUnit.SECONDS);
|
||||
dataManager = new BungeeDataManager(this);
|
||||
getProxy().getPluginManager().registerListener(this, new RedisBungeeListener(this, configuration.getExemptAddresses()));
|
||||
getProxy().getPluginManager().registerListener(this, dataManager);
|
||||
psl = new PubSubListener(this);
|
||||
getProxy().getScheduler().runAsync(this, psl);
|
||||
integrityCheck = service.scheduleAtFixedRate(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try (Jedis tmpRsc = requestJedis()) {
|
||||
Set<String> players = getLocalPlayersAsUuidStrings();
|
||||
Set<String> playersInRedis = tmpRsc.smembers("proxy:" + configuration.getServerId() + ":usersOnline");
|
||||
List<String> lagged = getCurrentServerIds(false, true);
|
||||
|
||||
// Clean up lagged players.
|
||||
for (String s : lagged) {
|
||||
Set<String> laggedPlayers = tmpRsc.smembers("proxy:" + s + ":usersOnline");
|
||||
tmpRsc.del("proxy:" + s + ":usersOnline");
|
||||
if (!laggedPlayers.isEmpty()) {
|
||||
getLogger().info("Cleaning up lagged proxy " + s + " (" + laggedPlayers.size() + " players)...");
|
||||
for (String laggedPlayer : laggedPlayers) {
|
||||
RedisUtil.cleanUpPlayer(laggedPlayer, tmpRsc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> absentLocally = new HashSet<>(playersInRedis);
|
||||
absentLocally.removeAll(players);
|
||||
Set<String> absentInRedis = new HashSet<>(players);
|
||||
absentInRedis.removeAll(playersInRedis);
|
||||
|
||||
for (String member : absentLocally) {
|
||||
boolean found = false;
|
||||
for (String proxyId : getServerIds()) {
|
||||
if (proxyId.equals(configuration.getServerId())) continue;
|
||||
if (tmpRsc.sismember("proxy:" + proxyId + ":usersOnline", member)) {
|
||||
// Just clean up the set.
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
RedisUtil.cleanUpPlayer(member, tmpRsc);
|
||||
getLogger().warning("Player found in set that was not found locally and globally: " + member);
|
||||
} else {
|
||||
tmpRsc.srem("proxy:" + configuration.getServerId() + ":usersOnline", member);
|
||||
getLogger().warning("Player found in set that was not found locally, but is on another proxy: " + member);
|
||||
}
|
||||
}
|
||||
|
||||
Pipeline pipeline = tmpRsc.pipelined();
|
||||
|
||||
for (String player : absentInRedis) {
|
||||
// Player not online according to Redis but not BungeeCord.
|
||||
getLogger().warning("Player " + player + " is on the proxy but not in Redis.");
|
||||
|
||||
ProxiedPlayer proxiedPlayer = ProxyServer.getInstance().getPlayer(UUID.fromString(player));
|
||||
if (proxiedPlayer == null)
|
||||
continue; // We'll deal with it later.
|
||||
|
||||
RBUtils.createPlayer(proxiedPlayer, pipeline, true);
|
||||
}
|
||||
|
||||
pipeline.sync();
|
||||
} catch (Throwable e) {
|
||||
getLogger().log(Level.SEVERE, "Unable to fix up stored player data", e);
|
||||
}
|
||||
}
|
||||
}, 0, 1, TimeUnit.MINUTES);
|
||||
}
|
||||
getProxy().registerChannel("legacy:redisbungee");
|
||||
getProxy().registerChannel("RedisBungee");
|
||||
// register commands
|
||||
if (configuration.doOverrideBungeeCommands()) {
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.GlistCommand(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.FindCommand(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.LastSeenCommand(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.IpCommand(this));
|
||||
}
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.SendToAll(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.ServerId(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.ServerIds(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.PlayerProxyCommand(this));
|
||||
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.PlistCommand(this));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disable() {
|
||||
if (isJedisAvailable()) {
|
||||
// Poison the PubSub listener
|
||||
psl.poison();
|
||||
integrityCheck.cancel(true);
|
||||
heartbeatTask.cancel(true);
|
||||
getProxy().getPluginManager().unregisterListeners(this);
|
||||
|
||||
try (Jedis tmpRsc = requestJedis()) {
|
||||
tmpRsc.hdel("heartbeats", configuration.getServerId());
|
||||
if (tmpRsc.scard("proxy:" + configuration.getServerId() + ":usersOnline") > 0) {
|
||||
Set<String> players = tmpRsc.smembers("proxy:" + configuration.getServerId() + ":usersOnline");
|
||||
for (String member : players)
|
||||
RedisUtil.cleanUpPlayer(member, tmpRsc);
|
||||
}
|
||||
}
|
||||
|
||||
this.jedisPool.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadConfig() throws IOException {
|
||||
if (!getDataFolder().exists()) {
|
||||
getDataFolder().mkdir();
|
||||
}
|
||||
|
||||
File file = new File(getDataFolder(), "config.yml");
|
||||
|
||||
if (!file.exists()) {
|
||||
file.createNewFile();
|
||||
try (InputStream in = getResourceAsStream("example_config.yml");
|
||||
OutputStream out = new FileOutputStream(file)) {
|
||||
ByteStreams.copy(in, out);
|
||||
}
|
||||
}
|
||||
|
||||
final Configuration yamlConfiguration = ConfigurationProvider.getProvider(YamlConfiguration.class).load(file);
|
||||
|
||||
final String redisServer = yamlConfiguration.getString("redis-server", "localhost");
|
||||
final int redisPort = yamlConfiguration.getInt("redis-port", 6379);
|
||||
final boolean useSSL = yamlConfiguration.getBoolean("useSSL", false);
|
||||
String redisPassword = yamlConfiguration.getString("redis-password", "");
|
||||
String serverId = yamlConfiguration.getString("server-id");
|
||||
|
||||
// check redis password
|
||||
if (redisPassword != null && (redisPassword.isEmpty() || redisPassword.equals("none"))) {
|
||||
redisPassword = null;
|
||||
getLogger().warning("INSECURE setup was detected Please set password for your redis instance.");
|
||||
}
|
||||
if (!useSSL) {
|
||||
getLogger().warning("INSECURE setup was detected Please setup ssl for your redis instance.");
|
||||
}
|
||||
// Configuration sanity checks.
|
||||
if (serverId == null || serverId.isEmpty()) {
|
||||
/*
|
||||
* this check causes the config comments to disappear somehow
|
||||
* I think due snake yaml limitations so as todo: write our own yaml parser?
|
||||
*/
|
||||
String genId = UUID.randomUUID().toString();
|
||||
getLogger().info("Generated server id " + genId + " and saving it to config.");
|
||||
yamlConfiguration.set("server-id", genId);
|
||||
ConfigurationProvider.getProvider(YamlConfiguration.class).save(yamlConfiguration, new File(getDataFolder(), "config.yml"));
|
||||
getLogger().info("Server id was generated: " + serverId);
|
||||
} else {
|
||||
getLogger().info("Loaded server id " + serverId + '.');
|
||||
}
|
||||
this.configuration = new RedisBungeeConfiguration(serverId, yamlConfiguration.getStringList("exempt-ip-addresses"), yamlConfiguration.getBoolean("register-bungee-commands", true));
|
||||
|
||||
if (redisServer != null && !redisServer.isEmpty()) {
|
||||
try {
|
||||
JedisPoolConfig config = new JedisPoolConfig();
|
||||
config.setMaxTotal(yamlConfiguration.getInt("max-redis-connections", 8));
|
||||
this.jedisPool = new JedisPool(config, redisServer, redisPort, 0, redisPassword, useSSL);
|
||||
|
||||
} catch (JedisConnectionException e) {
|
||||
throw new RuntimeException("Unable to create Redis pool", e);
|
||||
}
|
||||
|
||||
// Test the connection
|
||||
try (Jedis rsc = requestJedis()) {
|
||||
rsc.ping();
|
||||
// If that worked, now we can check for an existing, alive Bungee:
|
||||
File crashFile = new File(getDataFolder(), "restarted_from_crash.txt");
|
||||
if (crashFile.exists()) {
|
||||
crashFile.delete();
|
||||
} else if (rsc.hexists("heartbeats", serverId)) {
|
||||
try {
|
||||
long value = Long.parseLong(rsc.hget("heartbeats", serverId));
|
||||
long redisTime = getRedisTime(rsc.time());
|
||||
if (redisTime < value + 20) {
|
||||
getLogger().severe("You have launched a possible impostor BungeeCord instance. Another instance is already running.");
|
||||
getLogger().severe("For data consistency reasons, RedisBungee will now disable itself.");
|
||||
getLogger().severe("If this instance is coming up from a crash, create a file in your RedisBungee plugins directory with the name 'restarted_from_crash.txt' and RedisBungee will not perform this check.");
|
||||
throw new RuntimeException("Possible impostor instance!");
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
httpClient = new OkHttpClient();
|
||||
Dispatcher dispatcher = new Dispatcher(getExecutorService());
|
||||
httpClient.setDispatcher(dispatcher);
|
||||
NameFetcher.setHttpClient(httpClient);
|
||||
UUIDFetcher.setHttpClient(httpClient);
|
||||
|
||||
getLogger().log(Level.INFO, "Successfully connected to Redis.");
|
||||
} catch (JedisConnectionException e) {
|
||||
this.jedisPool.destroy();
|
||||
this.jedisPool = null;
|
||||
throw e;
|
||||
}
|
||||
} else {
|
||||
throw new RuntimeException("No redis server specified!");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
enable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
disable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getPubSubEventClass() {
|
||||
return PubSubMessageEvent.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getNetworkJoinEventClass() {
|
||||
return PlayerJoinedNetworkEvent.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getServerChangeEventClass() {
|
||||
return PlayerChangedServerNetworkEvent.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getNetworkQuitEventClass() {
|
||||
return PlayerJoinedNetworkEvent.class;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,13 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import net.md_5.bungee.api.CommandSender;
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.commands;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.collect.HashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.imaginarycode.minecraft.redisbungee.RedisBungeeAPI;
|
||||
import com.imaginarycode.minecraft.redisbungee.RedisBungeeBungeePlugin;
|
||||
import com.imaginarycode.minecraft.redisbungee.internal.RedisBungeePlugin;
|
||||
import com.imaginarycode.minecraft.redisbungee.RedisBungee;
|
||||
import com.imaginarycode.minecraft.redisbungee.AbstractRedisBungeeAPI;
|
||||
import net.md_5.bungee.api.ChatColor;
|
||||
import net.md_5.bungee.api.CommandSender;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.api.chat.ComponentBuilder;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.md_5.bungee.api.config.ServerInfo;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.plugin.Command;
|
||||
|
||||
import java.net.InetAddress;
|
||||
@@ -25,7 +33,7 @@ import java.util.UUID;
|
||||
/**
|
||||
* This class contains subclasses that are used for the commands RedisBungee overrides or includes: /glist, /find and /lastseen.
|
||||
* <p>
|
||||
* All classes use the {@link RedisBungeeAPI}.
|
||||
* All classes use the {@link AbstractRedisBungeeAPI}.
|
||||
*
|
||||
* @author tuxed
|
||||
* @since 0.2.3
|
||||
@@ -43,9 +51,9 @@ public class RedisBungeeCommands {
|
||||
}
|
||||
|
||||
public static class GlistCommand extends Command {
|
||||
private final RedisBungeeBungeePlugin plugin;
|
||||
private final RedisBungee plugin;
|
||||
|
||||
public GlistCommand(RedisBungeeBungeePlugin plugin) {
|
||||
public GlistCommand(RedisBungee plugin) {
|
||||
super("glist", "bungeecord.command.list", "redisbungee", "rglist");
|
||||
this.plugin = plugin;
|
||||
}
|
||||
@@ -55,14 +63,16 @@ public class RedisBungeeCommands {
|
||||
plugin.getProxy().getScheduler().runAsync(plugin, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
int count = plugin.getApi().getPlayerCount();
|
||||
int count = plugin.getAbstractRedisBungeeApi().getPlayerCount();
|
||||
BaseComponent[] playersOnline = new ComponentBuilder("").color(ChatColor.YELLOW)
|
||||
.append(playerPlural(count) + " currently online.").create();
|
||||
if (args.length > 0 && args[0].equals("showall")) {
|
||||
Multimap<String, UUID> serverToPlayers = plugin.getApi().getServerToPlayers();
|
||||
Multimap<String, UUID> serverToPlayers = plugin.getAbstractRedisBungeeApi().getServerToPlayers();
|
||||
Multimap<String, String> human = HashMultimap.create();
|
||||
for (Map.Entry<String, UUID> entry : serverToPlayers.entries()) {
|
||||
human.put(entry.getKey(), plugin.getUuidTranslator().getNameFromUuid(entry.getValue(), false));
|
||||
// if for any reason UUID translation fails just return the uuid as name, to make command finish executing.
|
||||
String playerName = plugin.getUuidTranslator().getNameFromUuid(entry.getValue(), false);
|
||||
human.put(entry.getKey(), playerName != null ? playerName : entry.getValue().toString());
|
||||
}
|
||||
for (String server : new TreeSet<>(serverToPlayers.keySet())) {
|
||||
TextComponent serverName = new TextComponent();
|
||||
@@ -87,9 +97,9 @@ public class RedisBungeeCommands {
|
||||
}
|
||||
|
||||
public static class FindCommand extends Command {
|
||||
private final RedisBungeeBungeePlugin plugin;
|
||||
private final RedisBungee plugin;
|
||||
|
||||
public FindCommand(RedisBungeeBungeePlugin plugin) {
|
||||
public FindCommand(RedisBungee plugin) {
|
||||
super("find", "bungeecord.command.find", "rfind");
|
||||
this.plugin = plugin;
|
||||
}
|
||||
@@ -105,7 +115,7 @@ public class RedisBungeeCommands {
|
||||
sender.sendMessage(PLAYER_NOT_FOUND);
|
||||
return;
|
||||
}
|
||||
ServerInfo si = plugin.getProxy().getServerInfo(plugin.getApi().getServerFor(uuid));
|
||||
ServerInfo si = plugin.getProxy().getServerInfo(plugin.getAbstractRedisBungeeApi().getServerNameFor(uuid));
|
||||
if (si != null) {
|
||||
TextComponent message = new TextComponent();
|
||||
message.setColor(ChatColor.BLUE);
|
||||
@@ -123,9 +133,9 @@ public class RedisBungeeCommands {
|
||||
}
|
||||
|
||||
public static class LastSeenCommand extends Command {
|
||||
private final RedisBungeeBungeePlugin plugin;
|
||||
private final RedisBungee plugin;
|
||||
|
||||
public LastSeenCommand(RedisBungeeBungeePlugin plugin) {
|
||||
public LastSeenCommand(RedisBungee plugin) {
|
||||
super("lastseen", "redisbungee.command.lastseen", "rlastseen");
|
||||
this.plugin = plugin;
|
||||
}
|
||||
@@ -141,7 +151,7 @@ public class RedisBungeeCommands {
|
||||
sender.sendMessage(PLAYER_NOT_FOUND);
|
||||
return;
|
||||
}
|
||||
long secs = plugin.getApi().getLastOnline(uuid);
|
||||
long secs = plugin.getAbstractRedisBungeeApi().getLastOnline(uuid);
|
||||
TextComponent message = new TextComponent();
|
||||
if (secs == 0) {
|
||||
message.setColor(ChatColor.GREEN);
|
||||
@@ -163,9 +173,9 @@ public class RedisBungeeCommands {
|
||||
}
|
||||
|
||||
public static class IpCommand extends Command {
|
||||
private final RedisBungeeBungeePlugin plugin;
|
||||
private final RedisBungee plugin;
|
||||
|
||||
public IpCommand(RedisBungeeBungeePlugin plugin) {
|
||||
public IpCommand(RedisBungee plugin) {
|
||||
super("ip", "redisbungee.command.ip", "playerip", "rip", "rplayerip");
|
||||
this.plugin = plugin;
|
||||
}
|
||||
@@ -181,7 +191,7 @@ public class RedisBungeeCommands {
|
||||
sender.sendMessage(PLAYER_NOT_FOUND);
|
||||
return;
|
||||
}
|
||||
InetAddress ia = plugin.getApi().getPlayerIp(uuid);
|
||||
InetAddress ia = plugin.getAbstractRedisBungeeApi().getPlayerIp(uuid);
|
||||
if (ia != null) {
|
||||
TextComponent message = new TextComponent();
|
||||
message.setColor(ChatColor.GREEN);
|
||||
@@ -199,9 +209,9 @@ public class RedisBungeeCommands {
|
||||
}
|
||||
|
||||
public static class PlayerProxyCommand extends Command {
|
||||
private final RedisBungeeBungeePlugin plugin;
|
||||
private final RedisBungee plugin;
|
||||
|
||||
public PlayerProxyCommand(RedisBungeeBungeePlugin plugin) {
|
||||
public PlayerProxyCommand(RedisBungee plugin) {
|
||||
super("pproxy", "redisbungee.command.pproxy");
|
||||
this.plugin = plugin;
|
||||
}
|
||||
@@ -217,7 +227,7 @@ public class RedisBungeeCommands {
|
||||
sender.sendMessage(PLAYER_NOT_FOUND);
|
||||
return;
|
||||
}
|
||||
String proxy = plugin.getApi().getProxy(uuid);
|
||||
String proxy = plugin.getAbstractRedisBungeeApi().getProxy(uuid);
|
||||
if (proxy != null) {
|
||||
TextComponent message = new TextComponent();
|
||||
message.setColor(ChatColor.GREEN);
|
||||
@@ -235,9 +245,9 @@ public class RedisBungeeCommands {
|
||||
}
|
||||
|
||||
public static class SendToAll extends Command {
|
||||
private final RedisBungeeBungeePlugin plugin;
|
||||
private final RedisBungee plugin;
|
||||
|
||||
public SendToAll(RedisBungeeBungeePlugin plugin) {
|
||||
public SendToAll(RedisBungee plugin) {
|
||||
super("sendtoall", "redisbungee.command.sendtoall", "rsendtoall");
|
||||
this.plugin = plugin;
|
||||
}
|
||||
@@ -246,7 +256,7 @@ public class RedisBungeeCommands {
|
||||
public void execute(CommandSender sender, String[] args) {
|
||||
if (args.length > 0) {
|
||||
String command = Joiner.on(" ").skipNulls().join(args);
|
||||
plugin.getApi().sendProxyCommand(command);
|
||||
plugin.getAbstractRedisBungeeApi().sendProxyCommand(command);
|
||||
TextComponent message = new TextComponent();
|
||||
message.setColor(ChatColor.GREEN);
|
||||
message.setText("Sent the command /" + command + " to all proxies.");
|
||||
@@ -258,9 +268,9 @@ public class RedisBungeeCommands {
|
||||
}
|
||||
|
||||
public static class ServerId extends Command {
|
||||
private final RedisBungeeBungeePlugin plugin;
|
||||
private final RedisBungee plugin;
|
||||
|
||||
public ServerId(RedisBungeeBungeePlugin plugin) {
|
||||
public ServerId(RedisBungee plugin) {
|
||||
super("serverid", "redisbungee.command.serverid", "rserverid");
|
||||
this.plugin = plugin;
|
||||
}
|
||||
@@ -268,15 +278,15 @@ public class RedisBungeeCommands {
|
||||
@Override
|
||||
public void execute(CommandSender sender, String[] args) {
|
||||
TextComponent textComponent = new TextComponent();
|
||||
textComponent.setText("You are on " + plugin.getApi().getServerId() + ".");
|
||||
textComponent.setText("You are on " + plugin.getAbstractRedisBungeeApi().getProxyId() + ".");
|
||||
textComponent.setColor(ChatColor.YELLOW);
|
||||
sender.sendMessage(textComponent);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ServerIds extends Command {
|
||||
private final RedisBungeeBungeePlugin plugin;
|
||||
public ServerIds(RedisBungeeBungeePlugin plugin) {
|
||||
private final RedisBungee plugin;
|
||||
public ServerIds(RedisBungee plugin) {
|
||||
super("serverids", "redisbungee.command.serverids");
|
||||
this.plugin =plugin;
|
||||
}
|
||||
@@ -284,16 +294,16 @@ public class RedisBungeeCommands {
|
||||
@Override
|
||||
public void execute(CommandSender sender, String[] strings) {
|
||||
TextComponent textComponent = new TextComponent();
|
||||
textComponent.setText("All server IDs: " + Joiner.on(", ").join(plugin.getApi().getAllServers()));
|
||||
textComponent.setText("All server IDs: " + Joiner.on(", ").join(plugin.getAbstractRedisBungeeApi().getAllProxies()));
|
||||
textComponent.setColor(ChatColor.YELLOW);
|
||||
sender.sendMessage(textComponent);
|
||||
}
|
||||
}
|
||||
|
||||
public static class PlistCommand extends Command {
|
||||
private final RedisBungeeBungeePlugin plugin;
|
||||
private final RedisBungee plugin;
|
||||
|
||||
public PlistCommand(RedisBungeeBungeePlugin plugin) {
|
||||
public PlistCommand(RedisBungee plugin) {
|
||||
super("plist", "redisbungee.command.plist", "rplist");
|
||||
this.plugin = plugin;
|
||||
}
|
||||
@@ -303,16 +313,16 @@ public class RedisBungeeCommands {
|
||||
plugin.getProxy().getScheduler().runAsync(plugin, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
String proxy = args.length >= 1 ? args[0] : plugin.getConfiguration().getServerId();
|
||||
if (!plugin.getServerIds().contains(proxy)) {
|
||||
String proxy = args.length >= 1 ? args[0] : plugin.getConfiguration().getProxyId();
|
||||
if (!plugin.getProxiesIds().contains(proxy)) {
|
||||
sender.sendMessage(new ComponentBuilder(proxy + " is not a valid proxy. See /serverids for valid proxies.").color(ChatColor.RED).create());
|
||||
return;
|
||||
}
|
||||
Set<UUID> players = plugin.getApi().getPlayersOnProxy(proxy);
|
||||
Set<UUID> players = plugin.getAbstractRedisBungeeApi().getPlayersOnProxy(proxy);
|
||||
BaseComponent[] playersOnline = new ComponentBuilder("").color(ChatColor.YELLOW)
|
||||
.append(playerPlural(players.size()) + " currently on proxy " + proxy + ".").create();
|
||||
if (args.length >= 2 && args[1].equals("showall")) {
|
||||
Multimap<String, UUID> serverToPlayers = plugin.getApi().getServerToPlayers();
|
||||
Multimap<String, UUID> serverToPlayers = plugin.getAbstractRedisBungeeApi().getServerToPlayers();
|
||||
Multimap<String, String> human = HashMultimap.create();
|
||||
for (Map.Entry<String, UUID> entry : serverToPlayers.entries()) {
|
||||
if (players.contains(entry.getValue())) {
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.events;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPlayerChangedServerNetworkEvent;
|
||||
import net.md_5.bungee.api.plugin.Event;
|
||||
|
||||
import java.util.UUID;
|
||||
@@ -13,7 +24,7 @@ import java.util.UUID;
|
||||
*
|
||||
* @since 0.3.4
|
||||
*/
|
||||
public class PlayerChangedServerNetworkEvent extends Event {
|
||||
public class PlayerChangedServerNetworkEvent extends Event implements IPlayerChangedServerNetworkEvent {
|
||||
private final UUID uuid;
|
||||
private final String previousServer;
|
||||
private final String server;
|
||||
@@ -24,14 +35,17 @@ public class PlayerChangedServerNetworkEvent extends Event {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUuid() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getServer() {
|
||||
return server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPreviousServer() {
|
||||
return previousServer;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.events;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPlayerJoinedNetworkEvent;
|
||||
import net.md_5.bungee.api.plugin.Event;
|
||||
|
||||
import java.util.UUID;
|
||||
@@ -13,13 +24,14 @@ import java.util.UUID;
|
||||
*
|
||||
* @since 0.3.4
|
||||
*/
|
||||
public class PlayerJoinedNetworkEvent extends Event {
|
||||
public class PlayerJoinedNetworkEvent extends Event implements IPlayerJoinedNetworkEvent {
|
||||
private final UUID uuid;
|
||||
|
||||
public PlayerJoinedNetworkEvent(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUuid() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.events;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPlayerLeftNetworkEvent;
|
||||
import net.md_5.bungee.api.plugin.Event;
|
||||
|
||||
import java.util.UUID;
|
||||
@@ -13,13 +24,14 @@ import java.util.UUID;
|
||||
*
|
||||
* @since 0.3.4
|
||||
*/
|
||||
public class PlayerLeftNetworkEvent extends Event {
|
||||
public class PlayerLeftNetworkEvent extends Event implements IPlayerLeftNetworkEvent {
|
||||
private final UUID uuid;
|
||||
|
||||
public PlayerLeftNetworkEvent(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUuid() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.events;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPubSubMessageEvent;
|
||||
import net.md_5.bungee.api.plugin.Event;
|
||||
|
||||
/**
|
||||
@@ -10,7 +21,7 @@ import net.md_5.bungee.api.plugin.Event;
|
||||
* @since 0.2.6
|
||||
*/
|
||||
|
||||
public class PubSubMessageEvent extends Event {
|
||||
public class PubSubMessageEvent extends Event implements IPubSubMessageEvent {
|
||||
private final String channel;
|
||||
private final String message;
|
||||
|
||||
@@ -19,10 +30,12 @@ public class PubSubMessageEvent extends Event {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getChannel() {
|
||||
return channel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
name: RedisBungee
|
||||
main: com.imaginarycode.minecraft.redisbungee.RedisBungeeBungeePlugin
|
||||
version: ${project.version}
|
||||
author: Chunkr and Govindas limework
|
||||
authors:
|
||||
- chunkr
|
||||
- Govindas Limework
|
||||
main: com.imaginarycode.minecraft.redisbungee.RedisBungee
|
||||
version: *{redisbungee.version}*
|
||||
author: "astei, ProxioDev"
|
||||
# This is used so that we can automatically override default BungeeCord behavior.
|
||||
softDepends: ["cmd_find", "cmd_list"]
|
||||
74
RedisBungee-Velocity/build.gradle.kts
Normal file
74
RedisBungee-Velocity/build.gradle.kts
Normal file
@@ -0,0 +1,74 @@
|
||||
plugins {
|
||||
`java-library`
|
||||
`maven-publish`
|
||||
id("com.github.johnrengelman.shadow") version "8.1.1"
|
||||
id("xyz.jpenilla.run-velocity") version "2.0.0"
|
||||
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://repo.papermc.io/repository/maven-public/") }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api(project(":RedisBungee-API")) {
|
||||
// Since velocity already includes guava / configurate exlude them
|
||||
exclude("com.google.guava", "guava")
|
||||
exclude("com.google.code.gson", "gson")
|
||||
exclude("org.spongepowered", "configurate-yaml")
|
||||
}
|
||||
compileOnly("com.velocitypowered:velocity-api:3.2.0-SNAPSHOT")
|
||||
annotationProcessor("com.velocitypowered:velocity-api:3.2.0-SNAPSHOT")
|
||||
}
|
||||
|
||||
description = "RedisBungee Velocity implementation"
|
||||
|
||||
java {
|
||||
withJavadocJar()
|
||||
withSourcesJar()
|
||||
}
|
||||
|
||||
tasks {
|
||||
withType<Javadoc> {
|
||||
dependsOn(project(":RedisBungee-API").getTasksByName("javadoc", false))
|
||||
val options = options as StandardJavadocDocletOptions
|
||||
options.use()
|
||||
options.isDocFilesSubDirs = true
|
||||
options.links(
|
||||
"https://jd.papermc.io/velocity/3.0.0/", // velocity api
|
||||
)
|
||||
val apiDocs = File(rootProject.projectDir, "RedisBungee-API/build/docs/javadoc")
|
||||
options.linksOffline("https://ci.limework.net/RedisBungee/RedisBungee-API/build/docs/javadoc", apiDocs.path)
|
||||
}
|
||||
runVelocity {
|
||||
velocityVersion("3.2.0-SNAPSHOT")
|
||||
}
|
||||
compileJava {
|
||||
options.encoding = Charsets.UTF_8.name()
|
||||
options.release.set(11)
|
||||
}
|
||||
javadoc {
|
||||
options.encoding = Charsets.UTF_8.name()
|
||||
}
|
||||
processResources {
|
||||
filteringCharset = Charsets.UTF_8.name()
|
||||
}
|
||||
shadowJar {
|
||||
relocate("redis.clients.jedis", "com.imaginarycode.minecraft.redisbungee.internal.jedis")
|
||||
relocate("redis.clients.util", "com.imaginarycode.minecraft.redisbungee.internal.jedisutil")
|
||||
relocate("org.apache.commons.pool", "com.imaginarycode.minecraft.redisbungee.internal.commonspool")
|
||||
relocate("com.squareup.okhttp", "com.imaginarycode.minecraft.redisbungee.internal.okhttp")
|
||||
relocate("okio", "com.imaginarycode.minecraft.redisbungee.internal.okio")
|
||||
relocate("org.json", "com.imaginarycode.minecraft.redisbungee.internal.json")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
create<MavenPublication>("maven") {
|
||||
from(components["java"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import com.velocitypowered.api.proxy.server.RegisteredServer;
|
||||
import com.velocitypowered.api.proxy.server.ServerInfo;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* This platform class exposes some internal RedisBungee functions. You obtain an instance of this object by invoking {@link RedisBungeeAPI#getRedisBungeeApi()}
|
||||
* or somehow you got the Plugin instance by you can call the api using {@link RedisBungeePlugin#getAbstractRedisBungeeApi()}.
|
||||
*
|
||||
* @author tuxed
|
||||
* @since 0.2.3 | updated 0.8.0
|
||||
*/
|
||||
public class RedisBungeeAPI extends AbstractRedisBungeeAPI {
|
||||
|
||||
private static RedisBungeeAPI redisBungeeApi;
|
||||
|
||||
public RedisBungeeAPI(RedisBungeePlugin<?> plugin) {
|
||||
super(plugin);
|
||||
if (redisBungeeApi == null) {
|
||||
redisBungeeApi = this;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the server where the specified player is playing. This function also deals with the case of local players
|
||||
* as well, and will return local information on them.
|
||||
*
|
||||
* @param player a player uuid
|
||||
* @return {@link ServerInfo} Can be null if proxy can't find it.
|
||||
* @see #getServerNameFor(UUID)
|
||||
*/
|
||||
@Nullable
|
||||
public final ServerInfo getServerFor(@NonNull UUID player) {
|
||||
String serverName = this.getServerNameFor(player);
|
||||
if (serverName == null) return null;
|
||||
return ((RedisBungeeVelocityPlugin) this.plugin).getProxy().getServer(serverName).map((RegisteredServer::getServerInfo)).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Api instance
|
||||
*
|
||||
* @return the API instance.
|
||||
* @since 0.6.5
|
||||
*/
|
||||
public static RedisBungeeAPI getRedisBungeeApi() {
|
||||
return redisBungeeApi;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
|
||||
import com.velocitypowered.api.command.CommandSource;
|
||||
import com.velocitypowered.api.permission.Tristate;
|
||||
import net.kyori.adventure.permission.PermissionChecker;
|
||||
|
||||
public class RedisBungeeCommandSource implements CommandSource {
|
||||
private static final RedisBungeeCommandSource singleton;
|
||||
private final PermissionChecker permissionChecker = PermissionChecker.always(net.kyori.adventure.util.TriState.TRUE);
|
||||
|
||||
static {
|
||||
singleton = new RedisBungeeCommandSource();
|
||||
}
|
||||
|
||||
public static RedisBungeeCommandSource getSingleton() {
|
||||
return singleton;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(String permission) {
|
||||
return this.permissionChecker.test(permission);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Tristate getPermissionValue(String s) {
|
||||
return Tristate.TRUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PermissionChecker getPermissionChecker() {
|
||||
return this.permissionChecker;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.collect.HashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.io.ByteArrayDataInput;
|
||||
import com.google.common.io.ByteArrayDataOutput;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.AbstractRedisBungeeListener;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.config.RedisBungeeConfiguration;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.player.PlayerUtils;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.tasks.RedisTask;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.payload.PayloadUtils;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PubSubMessageEvent;
|
||||
import com.velocitypowered.api.event.Continuation;
|
||||
import com.velocitypowered.api.event.PostOrder;
|
||||
import com.velocitypowered.api.event.ResultedEvent;
|
||||
import com.velocitypowered.api.event.Subscribe;
|
||||
import com.velocitypowered.api.event.connection.DisconnectEvent;
|
||||
import com.velocitypowered.api.event.connection.LoginEvent;
|
||||
import com.velocitypowered.api.event.connection.PluginMessageEvent;
|
||||
import com.velocitypowered.api.event.connection.PostLoginEvent;
|
||||
import com.velocitypowered.api.event.connection.PluginMessageEvent.ForwardResult;
|
||||
import com.velocitypowered.api.event.player.ServerConnectedEvent;
|
||||
import com.velocitypowered.api.event.proxy.ProxyPingEvent;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import com.velocitypowered.api.proxy.ServerConnection;
|
||||
import com.velocitypowered.api.proxy.server.ServerPing;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.imaginarycode.minecraft.redisbungee.api.util.serialize.Serializations.serializeMultimap;
|
||||
import static com.imaginarycode.minecraft.redisbungee.api.util.serialize.Serializations.serializeMultiset;
|
||||
|
||||
public class RedisBungeeVelocityListener extends AbstractRedisBungeeListener<LoginEvent, PostLoginEvent, DisconnectEvent, ServerConnectedEvent, ProxyPingEvent, PluginMessageEvent, PubSubMessageEvent> {
|
||||
// Some messages are using legacy characters
|
||||
private final LegacyComponentSerializer serializer = LegacyComponentSerializer.legacySection();
|
||||
|
||||
public RedisBungeeVelocityListener(RedisBungeePlugin<?> plugin, List<InetAddress> exemptAddresses) {
|
||||
super(plugin, exemptAddresses);
|
||||
}
|
||||
|
||||
@Subscribe(order = PostOrder.LAST)
|
||||
public void onLogin(LoginEvent event, Continuation continuation) {
|
||||
plugin.executeAsync(new RedisTask<Void>(plugin) {
|
||||
@Override
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
try {
|
||||
if (!event.getResult().isAllowed()) {
|
||||
return null;
|
||||
}
|
||||
if (plugin.getConfiguration().restoreOldKickBehavior()) {
|
||||
|
||||
for (String s : plugin.getProxiesIds()) {
|
||||
if (unifiedJedis.sismember("proxy:" + s + ":usersOnline", event.getPlayer().getUniqueId().toString())) {
|
||||
event.setResult(ResultedEvent.ComponentResult.denied(serializer.deserialize(plugin.getConfiguration().getMessages().get(RedisBungeeConfiguration.MessageType.ALREADY_LOGGED_IN))));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
} else if (api.isPlayerOnline(event.getPlayer().getUniqueId())) {
|
||||
PlayerUtils.setKickedOtherLocation(event.getPlayer().getUniqueId().toString(), unifiedJedis);
|
||||
api.kickPlayer(event.getPlayer().getUniqueId(), plugin.getConfiguration().getMessages().get(RedisBungeeConfiguration.MessageType.LOGGED_IN_OTHER_LOCATION));
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
continuation.resume();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@Subscribe
|
||||
public void onPostLogin(PostLoginEvent event) {
|
||||
plugin.executeAsync(new RedisTask<Void>(plugin) {
|
||||
@Override
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
plugin.getUuidTranslator().persistInfo(event.getPlayer().getUsername(), event.getPlayer().getUniqueId(), unifiedJedis);
|
||||
VelocityPlayerUtils.createVelocityPlayer(event.getPlayer(), unifiedJedis, true);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@Subscribe
|
||||
public void onPlayerDisconnect(DisconnectEvent event) {
|
||||
plugin.executeAsync(new RedisTask<Void>(plugin) {
|
||||
@Override
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
PlayerUtils.cleanUpPlayer(event.getPlayer().getUniqueId().toString(), unifiedJedis, true);
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@Subscribe
|
||||
public void onServerChange(ServerConnectedEvent event) {
|
||||
final String currentServer = event.getServer().getServerInfo().getName();
|
||||
final String oldServer = event.getPreviousServer().map(serverConnection -> serverConnection.getServerInfo().getName()).orElse(null);
|
||||
plugin.executeAsync(new RedisTask<Void>(plugin) {
|
||||
@Override
|
||||
public Void unifiedJedisTask(UnifiedJedis unifiedJedis) {
|
||||
unifiedJedis.hset("player:" + event.getPlayer().getUniqueId().toString(), "server", currentServer);
|
||||
PayloadUtils.playerServerChangePayload(event.getPlayer().getUniqueId(), unifiedJedis, currentServer, oldServer);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@Subscribe(order = PostOrder.LAST) // some plugins changes it online players so we need to be executed as last
|
||||
public void onPing(ProxyPingEvent event) {
|
||||
if (exemptAddresses.contains(event.getConnection().getRemoteAddress().getAddress())) {
|
||||
return;
|
||||
}
|
||||
ServerPing.Builder ping = event.getPing().asBuilder();
|
||||
ping.onlinePlayers(plugin.getCount());
|
||||
event.setPing(ping.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Subscribe
|
||||
public void onPluginMessage(PluginMessageEvent event) {
|
||||
if (!(event.getSource() instanceof ServerConnection) || !RedisBungeeVelocityPlugin.IDENTIFIERS.contains(event.getIdentifier())) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.setResult(ForwardResult.handled());
|
||||
|
||||
plugin.executeAsync(() -> {
|
||||
ByteArrayDataInput in = event.dataAsDataStream();
|
||||
|
||||
String subchannel = in.readUTF();
|
||||
ByteArrayDataOutput out = ByteStreams.newDataOutput();
|
||||
String type;
|
||||
|
||||
switch (subchannel) {
|
||||
case "PlayerList":
|
||||
out.writeUTF("PlayerList");
|
||||
Set<UUID> original = Collections.emptySet();
|
||||
type = in.readUTF();
|
||||
if (type.equals("ALL")) {
|
||||
out.writeUTF("ALL");
|
||||
original = plugin.getPlayers();
|
||||
} else {
|
||||
out.writeUTF(type);
|
||||
try {
|
||||
original = plugin.getAbstractRedisBungeeApi().getPlayersOnServer(type);
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
Set<String> players = original.stream()
|
||||
.map(uuid -> plugin.getUuidTranslator().getNameFromUuid(uuid, false))
|
||||
.collect(Collectors.toSet());
|
||||
out.writeUTF(Joiner.on(',').join(players));
|
||||
break;
|
||||
case "PlayerCount":
|
||||
out.writeUTF("PlayerCount");
|
||||
type = in.readUTF();
|
||||
if (type.equals("ALL")) {
|
||||
out.writeUTF("ALL");
|
||||
out.writeInt(plugin.getCount());
|
||||
} else {
|
||||
out.writeUTF(type);
|
||||
try {
|
||||
out.writeInt(plugin.getAbstractRedisBungeeApi().getPlayersOnServer(type).size());
|
||||
} catch (IllegalArgumentException e) {
|
||||
out.writeInt(0);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "LastOnline":
|
||||
String user = in.readUTF();
|
||||
out.writeUTF("LastOnline");
|
||||
out.writeUTF(user);
|
||||
out.writeLong(plugin.getAbstractRedisBungeeApi().getLastOnline(Objects.requireNonNull(plugin.getUuidTranslator().getTranslatedUuid(user, true))));
|
||||
break;
|
||||
case "ServerPlayers":
|
||||
String type1 = in.readUTF();
|
||||
out.writeUTF("ServerPlayers");
|
||||
Multimap<String, UUID> multimap = plugin.getAbstractRedisBungeeApi().getServerToPlayers();
|
||||
|
||||
boolean includesUsers;
|
||||
|
||||
switch (type1) {
|
||||
case "COUNT":
|
||||
includesUsers = false;
|
||||
break;
|
||||
case "PLAYERS":
|
||||
includesUsers = true;
|
||||
break;
|
||||
default:
|
||||
// TODO: Should I raise an error?
|
||||
return;
|
||||
}
|
||||
|
||||
out.writeUTF(type1);
|
||||
|
||||
if (includesUsers) {
|
||||
Multimap<String, String> human = HashMultimap.create();
|
||||
for (Map.Entry<String, UUID> entry : multimap.entries()) {
|
||||
human.put(entry.getKey(), plugin.getUuidTranslator().getNameFromUuid(entry.getValue(), false));
|
||||
}
|
||||
serializeMultimap(human, true, out);
|
||||
} else {
|
||||
serializeMultiset(multimap.keys(), out);
|
||||
}
|
||||
break;
|
||||
case "Proxy":
|
||||
out.writeUTF("Proxy");
|
||||
out.writeUTF(plugin.getConfiguration().getProxyId());
|
||||
break;
|
||||
case "PlayerProxy":
|
||||
String username = in.readUTF();
|
||||
out.writeUTF("PlayerProxy");
|
||||
out.writeUTF(username);
|
||||
out.writeUTF(plugin.getAbstractRedisBungeeApi().getProxy(Objects.requireNonNull(plugin.getUuidTranslator().getTranslatedUuid(username, true))));
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
((ServerConnection) event.getSource()).sendPluginMessage(event.getIdentifier(), out.toByteArray());
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@Subscribe
|
||||
public void onPubSubMessage(PubSubMessageEvent event) {
|
||||
if (event.getChannel().equals("redisbungee-allservers") || event.getChannel().equals("redisbungee-" + plugin.getAbstractRedisBungeeApi().getProxyId())) {
|
||||
String message = event.getMessage();
|
||||
if (message.startsWith("/"))
|
||||
message = message.substring(1);
|
||||
plugin.logInfo("Invoking command via PubSub: /" + message);
|
||||
((RedisBungeeVelocityPlugin) plugin).getProxy().getCommandManager().executeAsync(RedisBungeeCommandSource.getSingleton(), message);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.google.common.cache.Cache;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.inject.Inject;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.*;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.config.ConfigLoader;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.config.RedisBungeeConfiguration;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPlayerChangedServerNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPlayerJoinedNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPlayerLeftNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPubSubMessageEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.summoners.Summoner;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.tasks.*;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.uuid.NameFetcher;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.uuid.UUIDFetcher;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.uuid.UUIDTranslator;
|
||||
import com.imaginarycode.minecraft.redisbungee.commands.RedisBungeeCommands;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PlayerChangedServerNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PlayerJoinedNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PlayerLeftNetworkEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PubSubMessageEvent;
|
||||
import com.squareup.okhttp.Dispatcher;
|
||||
import com.squareup.okhttp.OkHttpClient;
|
||||
import com.velocitypowered.api.event.PostOrder;
|
||||
import com.velocitypowered.api.event.Subscribe;
|
||||
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
|
||||
import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
|
||||
import com.velocitypowered.api.plugin.Plugin;
|
||||
import com.velocitypowered.api.plugin.annotation.DataDirectory;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import com.velocitypowered.api.proxy.ProxyServer;
|
||||
import com.velocitypowered.api.proxy.messages.ChannelIdentifier;
|
||||
import com.velocitypowered.api.proxy.messages.LegacyChannelIdentifier;
|
||||
import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier;
|
||||
import com.velocitypowered.api.scheduler.ScheduledTask;
|
||||
import org.slf4j.Logger;
|
||||
import redis.clients.jedis.*;
|
||||
import redis.clients.jedis.exceptions.JedisConnectionException;
|
||||
|
||||
|
||||
import java.io.*;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@Plugin(id = "redisbungee", name = "RedisBungee", version = Constants.VERSION, url = "https://github.com/ProxioDev/RedisBungee", authors = {"astei", "ProxioDev"})
|
||||
public class RedisBungeeVelocityPlugin implements RedisBungeePlugin<Player>, ConfigLoader {
|
||||
private final ProxyServer server;
|
||||
private final Logger logger;
|
||||
private final Path dataFolder;
|
||||
private final AbstractRedisBungeeAPI api;
|
||||
private final PubSubListener psl;
|
||||
private Summoner<?> jedisSummoner;
|
||||
private RedisBungeeMode redisBungeeMode;
|
||||
private final UUIDTranslator uuidTranslator;
|
||||
private RedisBungeeConfiguration configuration;
|
||||
private final VelocityDataManager dataManager;
|
||||
private final OkHttpClient httpClient;
|
||||
private volatile List<String> proxiesIds;
|
||||
private final AtomicInteger globalPlayerCount = new AtomicInteger();
|
||||
private ScheduledTask integrityCheck;
|
||||
private ScheduledTask heartbeatTask;
|
||||
|
||||
private static final Object SERVER_TO_PLAYERS_KEY = new Object();
|
||||
public static final List<ChannelIdentifier> IDENTIFIERS = List.of(
|
||||
MinecraftChannelIdentifier.create("legacy", "redisbungee"),
|
||||
new LegacyChannelIdentifier("RedisBungee"),
|
||||
// This is needed for clients before 1.13
|
||||
new LegacyChannelIdentifier("legacy:redisbungee")
|
||||
);
|
||||
private final Cache<Object, Multimap<String, UUID>> serverToPlayersCache = CacheBuilder.newBuilder()
|
||||
.expireAfterWrite(5, TimeUnit.SECONDS)
|
||||
.build();
|
||||
|
||||
|
||||
@Inject
|
||||
public RedisBungeeVelocityPlugin(ProxyServer server, Logger logger, @DataDirectory Path dataDirectory) {
|
||||
this.server = server;
|
||||
this.logger = logger;
|
||||
this.dataFolder = dataDirectory;
|
||||
try {
|
||||
loadConfig(this, dataDirectory);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Unable to load/save config", e);
|
||||
} catch (JedisConnectionException e) {
|
||||
throw new RuntimeException("Unable to connect to your Redis server!", e);
|
||||
}
|
||||
this.api = new RedisBungeeAPI(this);
|
||||
InitialUtils.checkRedisVersion(this);
|
||||
// check if this proxy is recovering from a crash and start heart the beat.
|
||||
InitialUtils.checkIfRecovering(this, getDataFolder());
|
||||
uuidTranslator = new UUIDTranslator(this);
|
||||
dataManager = new VelocityDataManager(this);
|
||||
psl = new PubSubListener(this);
|
||||
this.httpClient = new OkHttpClient();
|
||||
Dispatcher dispatcher = new Dispatcher(Executors.newFixedThreadPool(6));
|
||||
this.httpClient.setDispatcher(dispatcher);
|
||||
//NameFetcher.setHttpClient(httpClient);
|
||||
UUIDFetcher.setHttpClient(httpClient);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public RedisBungeeConfiguration getConfiguration() {
|
||||
return this.configuration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCount() {
|
||||
return this.globalPlayerCount.get();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Set<String> getLocalPlayersAsUuidStrings() {
|
||||
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
|
||||
for (Player player : getProxy().getAllPlayers()) {
|
||||
builder.add(player.getUniqueId().toString());
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractDataManager<Player, ?, ?, ?> getDataManager() {
|
||||
return this.dataManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Summoner<?> getSummoner() {
|
||||
return this.jedisSummoner;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractRedisBungeeAPI getAbstractRedisBungeeApi() {
|
||||
return this.api;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUIDTranslator getUuidTranslator() {
|
||||
return this.uuidTranslator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Multimap<String, UUID> serverToPlayersCache() {
|
||||
try {
|
||||
return this.serverToPlayersCache.get(SERVER_TO_PLAYERS_KEY, this::serversToPlayers);
|
||||
} catch (ExecutionException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getProxiesIds() {
|
||||
return proxiesIds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PubSubListener getPubSubListener() {
|
||||
return this.psl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void executeAsync(Runnable runnable) {
|
||||
this.getProxy().getScheduler().buildTask(this, runnable).schedule();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void executeAsyncAfter(Runnable runnable, TimeUnit timeUnit, int time) {
|
||||
this.getProxy().getScheduler().buildTask(this, runnable).delay(time, timeUnit).schedule();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fireEvent(Object event) {
|
||||
this.getProxy().getEventManager().fireAndForget(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOnlineMode() {
|
||||
return this.getProxy().getConfiguration().isOnlineMode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void logInfo(String msg) {
|
||||
this.getLogger().info(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void logWarn(String msg) {
|
||||
this.getLogger().warn(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void logFatal(String msg) {
|
||||
this.getLogger().error(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Player getPlayer(UUID uuid) {
|
||||
return this.getProxy().getPlayer(uuid).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Player getPlayer(String name) {
|
||||
return this.getProxy().getPlayer(name).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getPlayerUUID(String player) {
|
||||
return this.getProxy().getPlayer(player).map(Player::getUniqueId).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlayerName(UUID player) {
|
||||
return this.getProxy().getPlayer(player).map(Player::getUsername).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlayerServerName(Player player) {
|
||||
return player.getCurrentServer().map(serverConnection -> serverConnection.getServerInfo().getName()).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayerOnAServer(Player player) {
|
||||
return player.getCurrentServer().isPresent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InetAddress getPlayerIp(Player player) {
|
||||
return player.getRemoteAddress().getAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize() {
|
||||
logInfo("Initializing RedisBungee.....");
|
||||
updateProxiesIds();
|
||||
// start heartbeat task
|
||||
heartbeatTask = getProxy().getScheduler().buildTask(this, new HeartbeatTask(this, this.globalPlayerCount)).repeat(HeartbeatTask.INTERVAL, HeartbeatTask.REPEAT_INTERVAL_TIME_UNIT).schedule();
|
||||
|
||||
getProxy().getEventManager().register(this, new RedisBungeeVelocityListener(this, configuration.getExemptAddresses()));
|
||||
getProxy().getEventManager().register(this, dataManager);
|
||||
getProxy().getScheduler().buildTask(this, psl).schedule();
|
||||
|
||||
IntegrityCheckTask integrityCheckTask = new IntegrityCheckTask(this) {
|
||||
@Override
|
||||
public void handlePlatformPlayer(String player, UnifiedJedis unifiedJedis) {
|
||||
Player playerProxied = getProxy().getPlayer(UUID.fromString(player)).orElse(null);
|
||||
if (playerProxied == null)
|
||||
return; // We'll deal with it later.
|
||||
VelocityPlayerUtils.createVelocityPlayer(playerProxied, unifiedJedis, false);
|
||||
}
|
||||
};
|
||||
integrityCheck = getProxy().getScheduler().buildTask(this, integrityCheckTask::execute).repeat(30, TimeUnit.SECONDS).schedule();
|
||||
|
||||
|
||||
// register plugin messages
|
||||
IDENTIFIERS.forEach(getProxy().getChannelRegistrar()::register);
|
||||
|
||||
// register legacy commands
|
||||
if (configuration.doRegisterLegacyCommands()) {
|
||||
// Override Velocity commands
|
||||
if (configuration.doOverrideBungeeCommands()) {
|
||||
getProxy().getCommandManager().register("glist", new RedisBungeeCommands.GlistCommand(this), "redisbungee", "rglist");
|
||||
}
|
||||
getProxy().getCommandManager().register("sendtoall", new RedisBungeeCommands.SendToAll(this), "rsendtoall");
|
||||
getProxy().getCommandManager().register("serverid", new RedisBungeeCommands.ServerId(this), "rserverid");
|
||||
getProxy().getCommandManager().register("serverids", new RedisBungeeCommands.ServerIds(this));
|
||||
getProxy().getCommandManager().register("pproxy", new RedisBungeeCommands.PlayerProxyCommand(this));
|
||||
getProxy().getCommandManager().register("plist", new RedisBungeeCommands.PlistCommand(this), "rplist");
|
||||
getProxy().getCommandManager().register("lastseen", new RedisBungeeCommands.LastSeenCommand(this), "rlastseen");
|
||||
getProxy().getCommandManager().register("ip", new RedisBungeeCommands.IpCommand(this), "playerip", "rip", "rplayerip");
|
||||
getProxy().getCommandManager().register("find", new RedisBungeeCommands.FindCommand(this), "rfind");
|
||||
}
|
||||
logInfo("RedisBungee initialized successfully ");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
logInfo("Turning off redis connections.....");
|
||||
// Poison the PubSub listener
|
||||
if (psl != null) {
|
||||
psl.poison();
|
||||
}
|
||||
if (integrityCheck != null) {
|
||||
integrityCheck.cancel();
|
||||
}
|
||||
if (heartbeatTask != null) {
|
||||
heartbeatTask.cancel();
|
||||
}
|
||||
ShutdownUtils.shutdownCleanup(this);
|
||||
try {
|
||||
this.jedisSummoner.close();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
this.httpClient.getDispatcher().getExecutorService().shutdown();
|
||||
try {
|
||||
logInfo("waiting for httpclient thread-pool termination.....");
|
||||
this.httpClient.getDispatcher().getExecutorService().awaitTermination(20, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
logInfo("RedisBungee shutdown complete");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConfigLoad(RedisBungeeConfiguration configuration, Summoner<?> summoner, RedisBungeeMode mode) {
|
||||
this.jedisSummoner = summoner;
|
||||
this.configuration = configuration;
|
||||
this.redisBungeeMode = mode;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public RedisBungeeMode getRedisBungeeMode() {
|
||||
return this.redisBungeeMode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateProxiesIds() {
|
||||
this.proxiesIds = this.getCurrentProxiesIds(false);
|
||||
}
|
||||
|
||||
@Subscribe(order = PostOrder.FIRST)
|
||||
public void onProxyInitializeEvent(ProxyInitializeEvent event) {
|
||||
initialize();
|
||||
}
|
||||
|
||||
@Subscribe(order = PostOrder.LAST)
|
||||
public void onProxyShutdownEvent(ProxyShutdownEvent event) {
|
||||
stop();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public IPlayerChangedServerNetworkEvent createPlayerChangedServerNetworkEvent(UUID uuid, String previousServer, String server) {
|
||||
return new PlayerChangedServerNetworkEvent(uuid, previousServer, server);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlayerJoinedNetworkEvent createPlayerJoinedNetworkEvent(UUID uuid) {
|
||||
return new PlayerJoinedNetworkEvent(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlayerLeftNetworkEvent createPlayerLeftNetworkEvent(UUID uuid) {
|
||||
return new PlayerLeftNetworkEvent(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPubSubMessageEvent createPubSubEvent(String channel, String message) {
|
||||
return new PubSubMessageEvent(channel, message);
|
||||
}
|
||||
|
||||
public ProxyServer getProxy() {
|
||||
return server;
|
||||
}
|
||||
|
||||
public Logger getLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
public Path getDataFolder() {
|
||||
return this.dataFolder;
|
||||
}
|
||||
|
||||
public InputStream getResourceAsStream(String name) {
|
||||
return this.getClass().getClassLoader().getResourceAsStream(name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.events.PubSubMessageEvent;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.AbstractDataManager;
|
||||
import com.imaginarycode.minecraft.redisbungee.api.RedisBungeePlugin;
|
||||
import com.velocitypowered.api.event.Subscribe;
|
||||
import com.velocitypowered.api.event.connection.DisconnectEvent;
|
||||
import com.velocitypowered.api.event.connection.PostLoginEvent;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
|
||||
public class VelocityDataManager extends AbstractDataManager<Player, PostLoginEvent, DisconnectEvent, PubSubMessageEvent> {
|
||||
|
||||
public VelocityDataManager(RedisBungeePlugin<Player> plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Subscribe
|
||||
public void onPostLogin(PostLoginEvent event) {
|
||||
invalidate(event.getPlayer().getUniqueId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Subscribe
|
||||
public void onPlayerDisconnect(DisconnectEvent event) {
|
||||
invalidate(event.getPlayer().getUniqueId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Subscribe
|
||||
public void onPubSubMessage(PubSubMessageEvent event) {
|
||||
handlePubSubMessage(event.getChannel(), event.getMessage());
|
||||
}
|
||||
|
||||
private final LegacyComponentSerializer serializer = LegacyComponentSerializer.legacySection();
|
||||
@Override
|
||||
public boolean handleKick(UUID target, String message) {
|
||||
Player player = plugin.getPlayer(target);
|
||||
if (player == null) {
|
||||
return false;
|
||||
}
|
||||
player.disconnect(serializer.deserialize(message));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee;
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.util.player.PlayerUtils;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import com.velocitypowered.api.proxy.ServerConnection;
|
||||
import redis.clients.jedis.UnifiedJedis;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class VelocityPlayerUtils {
|
||||
protected static void createVelocityPlayer(Player player, UnifiedJedis unifiedJedis, boolean fireEvent) {
|
||||
Optional<ServerConnection> optionalServerConnection = player.getCurrentServer();
|
||||
String serverName = null;
|
||||
if (optionalServerConnection.isPresent()) {
|
||||
serverName = optionalServerConnection.get().getServerInfo().getName();
|
||||
}
|
||||
PlayerUtils.createPlayer(player.getUniqueId(), unifiedJedis, serverName, player.getRemoteAddress().getAddress(), fireEvent);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.commands;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.UUID;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.collect.HashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.imaginarycode.minecraft.redisbungee.AbstractRedisBungeeAPI;
|
||||
import com.imaginarycode.minecraft.redisbungee.RedisBungeeVelocityPlugin;
|
||||
import com.velocitypowered.api.command.CommandSource;
|
||||
import com.velocitypowered.api.command.SimpleCommand;
|
||||
import com.velocitypowered.api.proxy.server.RegisteredServer;
|
||||
import com.velocitypowered.api.proxy.server.ServerInfo;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
|
||||
|
||||
/**
|
||||
* This class contains subclasses that are used for the commands RedisBungee overrides or includes: /glist, /find and /lastseen.
|
||||
* <p>
|
||||
* All classes use the {@link AbstractRedisBungeeAPI}.
|
||||
*
|
||||
* @author tuxed
|
||||
* @since 0.2.3
|
||||
*/
|
||||
public class RedisBungeeCommands {
|
||||
|
||||
private static final Component NO_PLAYER_SPECIFIED =
|
||||
Component.text("You must specify a player name.", NamedTextColor.RED);
|
||||
private static final Component PLAYER_NOT_FOUND =
|
||||
Component.text("No such player found.", NamedTextColor.RED);
|
||||
private static final Component NO_COMMAND_SPECIFIED =
|
||||
Component.text("You must specify a command to be run.", NamedTextColor.RED);
|
||||
|
||||
private static String playerPlural(int num) {
|
||||
return num == 1 ? num + " player is" : num + " players are";
|
||||
}
|
||||
|
||||
public static class GlistCommand implements SimpleCommand {
|
||||
private final RedisBungeeVelocityPlugin plugin;
|
||||
|
||||
public GlistCommand(RedisBungeeVelocityPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Invocation invocation) {
|
||||
plugin.getProxy().getScheduler().buildTask(plugin, () -> {
|
||||
int count = plugin.getAbstractRedisBungeeApi().getPlayerCount();
|
||||
Component playersOnline = Component.text(playerPlural(count) + " currently online.", NamedTextColor.YELLOW);
|
||||
CommandSource sender = invocation.source();
|
||||
if (invocation.arguments().length > 0 && invocation.arguments()[0].equals("showall")) {
|
||||
Multimap<String, UUID> serverToPlayers = plugin.getAbstractRedisBungeeApi().getServerToPlayers();
|
||||
Multimap<String, String> human = HashMultimap.create();
|
||||
serverToPlayers.forEach((key, value) -> {
|
||||
// if for any reason UUID translation fails just return the uuid as name, to make command finish executing.
|
||||
String playerName = plugin.getUuidTranslator().getNameFromUuid(value, false);
|
||||
human.put(key, playerName != null ? playerName : value.toString());
|
||||
});
|
||||
for (String server : new TreeSet<>(serverToPlayers.keySet())) {
|
||||
Component serverName = Component.text("[" + server + "] ", NamedTextColor.GREEN);
|
||||
Component serverCount = Component.text("(" + serverToPlayers.get(server).size() + "): ", NamedTextColor.YELLOW);
|
||||
Component serverPlayers = Component.text(Joiner.on(", ").join(human.get(server)), NamedTextColor.WHITE);
|
||||
sender.sendMessage(Component.textOfChildren(serverName, serverCount, serverPlayers));
|
||||
}
|
||||
sender.sendMessage(playersOnline);
|
||||
} else {
|
||||
sender.sendMessage(playersOnline);
|
||||
sender.sendMessage(Component.text("To see all players online, use /glist showall.", NamedTextColor.YELLOW));
|
||||
}
|
||||
}).schedule();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Invocation invocation) {
|
||||
return invocation.source().hasPermission("velocity.command.server");
|
||||
}
|
||||
}
|
||||
|
||||
public static class FindCommand implements SimpleCommand {
|
||||
private final RedisBungeeVelocityPlugin plugin;
|
||||
|
||||
public FindCommand(RedisBungeeVelocityPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Invocation invocation) {
|
||||
plugin.getProxy().getScheduler().buildTask(plugin, () -> {
|
||||
String[] args = invocation.arguments();
|
||||
CommandSource sender = invocation.source();
|
||||
if (args.length > 0) {
|
||||
UUID uuid = plugin.getUuidTranslator().getTranslatedUuid(args[0], true);
|
||||
if (uuid == null) {
|
||||
sender.sendMessage(PLAYER_NOT_FOUND);
|
||||
return;
|
||||
}
|
||||
ServerInfo si = plugin.getProxy().getServer(plugin.getAbstractRedisBungeeApi().getServerNameFor(uuid)).map(RegisteredServer::getServerInfo).orElse(null);
|
||||
if (si != null) {
|
||||
Component message = Component.text(args[0] + " is on " + si.getName() + ".", NamedTextColor.BLUE);
|
||||
sender.sendMessage(message);
|
||||
} else {
|
||||
sender.sendMessage(PLAYER_NOT_FOUND);
|
||||
}
|
||||
} else {
|
||||
sender.sendMessage(NO_PLAYER_SPECIFIED);
|
||||
}
|
||||
}).schedule();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Invocation invocation) {
|
||||
return invocation.source().hasPermission("redisbungee.command.find");
|
||||
}
|
||||
}
|
||||
|
||||
public static class LastSeenCommand implements SimpleCommand {
|
||||
private final RedisBungeeVelocityPlugin plugin;
|
||||
|
||||
public LastSeenCommand(RedisBungeeVelocityPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Invocation invocation) {
|
||||
plugin.getProxy().getScheduler().buildTask(plugin, () -> {
|
||||
String[] args = invocation.arguments();
|
||||
CommandSource sender = invocation.source();
|
||||
if (args.length > 0) {
|
||||
UUID uuid = plugin.getUuidTranslator().getTranslatedUuid(args[0], true);
|
||||
if (uuid == null) {
|
||||
sender.sendMessage(PLAYER_NOT_FOUND);
|
||||
return;
|
||||
}
|
||||
long secs = plugin.getAbstractRedisBungeeApi().getLastOnline(uuid);
|
||||
TextComponent.Builder message = Component.text();
|
||||
if (secs == 0) {
|
||||
message.color(NamedTextColor.GREEN);
|
||||
message.content(args[0] + " is currently online.");
|
||||
} else if (secs != -1) {
|
||||
message.color(NamedTextColor.BLUE);
|
||||
message.content(args[0] + " was last online on " + new SimpleDateFormat().format(secs) + ".");
|
||||
} else {
|
||||
message.color(NamedTextColor.RED);
|
||||
message.content(args[0] + " has never been online.");
|
||||
}
|
||||
sender.sendMessage(message.build());
|
||||
} else {
|
||||
sender.sendMessage(NO_PLAYER_SPECIFIED);
|
||||
}
|
||||
}).schedule();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Invocation invocation) {
|
||||
return invocation.source().hasPermission("redisbungee.command.lastseen");
|
||||
}
|
||||
}
|
||||
|
||||
public static class IpCommand implements SimpleCommand {
|
||||
private final RedisBungeeVelocityPlugin plugin;
|
||||
|
||||
public IpCommand(RedisBungeeVelocityPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Invocation invocation) {
|
||||
CommandSource sender = invocation.source();
|
||||
String[] args = invocation.arguments();
|
||||
plugin.getProxy().getScheduler().buildTask(plugin, () -> {
|
||||
if (args.length > 0) {
|
||||
UUID uuid = plugin.getUuidTranslator().getTranslatedUuid(args[0], true);
|
||||
if (uuid == null) {
|
||||
sender.sendMessage(PLAYER_NOT_FOUND);
|
||||
return;
|
||||
}
|
||||
InetAddress ia = plugin.getAbstractRedisBungeeApi().getPlayerIp(uuid);
|
||||
if (ia != null) {
|
||||
TextComponent message = Component.text(args[0] + " is connected from " + ia.toString() + ".", NamedTextColor.GREEN);
|
||||
sender.sendMessage(message);
|
||||
} else {
|
||||
sender.sendMessage(PLAYER_NOT_FOUND);
|
||||
}
|
||||
} else {
|
||||
sender.sendMessage(NO_PLAYER_SPECIFIED);
|
||||
}
|
||||
}).schedule();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Invocation invocation) {
|
||||
return invocation.source().hasPermission("redisbungee.command.ip");
|
||||
}
|
||||
}
|
||||
|
||||
public static class PlayerProxyCommand implements SimpleCommand {
|
||||
private final RedisBungeeVelocityPlugin plugin;
|
||||
|
||||
public PlayerProxyCommand(RedisBungeeVelocityPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Invocation invocation) {
|
||||
CommandSource sender = invocation.source();
|
||||
String[] args = invocation.arguments();
|
||||
plugin.getProxy().getScheduler().buildTask(plugin, () -> {
|
||||
if (args.length > 0) {
|
||||
UUID uuid = plugin.getUuidTranslator().getTranslatedUuid(args[0], true);
|
||||
if (uuid == null) {
|
||||
sender.sendMessage(PLAYER_NOT_FOUND);
|
||||
return;
|
||||
}
|
||||
String proxy = plugin.getAbstractRedisBungeeApi().getProxy(uuid);
|
||||
if (proxy != null) {
|
||||
TextComponent message = Component.text(args[0] + " is connected to " + proxy + ".", NamedTextColor.GREEN);
|
||||
sender.sendMessage(message);
|
||||
} else {
|
||||
sender.sendMessage(PLAYER_NOT_FOUND);
|
||||
}
|
||||
} else {
|
||||
sender.sendMessage(NO_PLAYER_SPECIFIED);
|
||||
}
|
||||
}).schedule();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Invocation invocation) {
|
||||
return invocation.source().hasPermission("redisbungee.command.pproxy");
|
||||
}
|
||||
}
|
||||
|
||||
public static class SendToAll implements SimpleCommand {
|
||||
private final RedisBungeeVelocityPlugin plugin;
|
||||
|
||||
public SendToAll(RedisBungeeVelocityPlugin plugin) {
|
||||
//super("sendtoall", "redisbungee.command.sendtoall", "rsendtoall");
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Invocation invocation) {
|
||||
String[] args = invocation.arguments();
|
||||
CommandSource sender = invocation.source();
|
||||
if (args.length > 0) {
|
||||
String command = Joiner.on(" ").skipNulls().join(args);
|
||||
plugin.getAbstractRedisBungeeApi().sendProxyCommand(command);
|
||||
TextComponent message = Component.text("Sent the command /" + command + " to all proxies.", NamedTextColor.GREEN);
|
||||
sender.sendMessage(message);
|
||||
} else {
|
||||
sender.sendMessage(NO_COMMAND_SPECIFIED);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Invocation invocation) {
|
||||
return invocation.source().hasPermission("redisbungee.command.sendtoall");
|
||||
}
|
||||
}
|
||||
|
||||
public static class ServerId implements SimpleCommand {
|
||||
private final RedisBungeeVelocityPlugin plugin;
|
||||
|
||||
public ServerId(RedisBungeeVelocityPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(Invocation invocation) {
|
||||
invocation.source().sendMessage(Component.text("You are on " + plugin.getAbstractRedisBungeeApi().getProxyId() + ".", NamedTextColor.YELLOW));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Invocation invocation) {
|
||||
return invocation.source().hasPermission("redisbungee.command.serverid");
|
||||
}
|
||||
}
|
||||
|
||||
public static class ServerIds implements SimpleCommand {
|
||||
private final RedisBungeeVelocityPlugin plugin;
|
||||
|
||||
public ServerIds(RedisBungeeVelocityPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(Invocation invocation) {
|
||||
invocation.source().sendMessage(
|
||||
Component.text("All server IDs: " + Joiner.on(", ").join(plugin.getAbstractRedisBungeeApi().getAllProxies()), NamedTextColor.YELLOW));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Invocation invocation) {
|
||||
return invocation.source().hasPermission("redisbungee.command.serverids");
|
||||
}
|
||||
}
|
||||
|
||||
public static class PlistCommand implements SimpleCommand {
|
||||
private final RedisBungeeVelocityPlugin plugin;
|
||||
|
||||
public PlistCommand(RedisBungeeVelocityPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(Invocation invocation) {
|
||||
CommandSource sender = invocation.source();
|
||||
String[] args = invocation.arguments();
|
||||
plugin.getProxy().getScheduler().buildTask(plugin, () -> {
|
||||
String proxy = args.length >= 1 ? args[0] : plugin.getConfiguration().getProxyId();
|
||||
if (!plugin.getProxiesIds().contains(proxy)) {
|
||||
sender.sendMessage(Component.text(proxy + " is not a valid proxy. See /serverids for valid proxies.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
Set<UUID> players = plugin.getAbstractRedisBungeeApi().getPlayersOnProxy(proxy);
|
||||
Component playersOnline = Component.text(playerPlural(players.size()) + " currently on proxy " + proxy + ".", NamedTextColor.YELLOW);
|
||||
if (args.length >= 2 && args[1].equals("showall")) {
|
||||
Multimap<String, UUID> serverToPlayers = plugin.getAbstractRedisBungeeApi().getServerToPlayers();
|
||||
Multimap<String, String> human = HashMultimap.create();
|
||||
serverToPlayers.forEach((key, value) -> {
|
||||
if (players.contains(value)) {
|
||||
human.put(key, plugin.getUuidTranslator().getNameFromUuid(value, false));
|
||||
}
|
||||
});
|
||||
for (String server : new TreeSet<>(human.keySet())) {
|
||||
TextComponent serverName = Component.text("[" + server + "] ", NamedTextColor.RED);
|
||||
TextComponent serverCount = Component.text("(" + human.get(server).size() + "): ", NamedTextColor.YELLOW);
|
||||
TextComponent serverPlayers = Component.text(Joiner.on(", ").join(human.get(server)), NamedTextColor.WHITE);
|
||||
sender.sendMessage(Component.textOfChildren(serverName, serverCount, serverPlayers));
|
||||
}
|
||||
sender.sendMessage(playersOnline);
|
||||
} else {
|
||||
sender.sendMessage(playersOnline);
|
||||
sender.sendMessage(Component.text("To see all players online, use /plist " + proxy + " showall.", NamedTextColor.YELLOW));
|
||||
}
|
||||
}).schedule();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Invocation invocation) {
|
||||
return invocation.source().hasPermission("redisbungee.command.plist");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.events;
|
||||
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPlayerChangedServerNetworkEvent;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* This event is sent when a player connects to a new server. RedisBungee sends the event only when
|
||||
* the proxy the player has been connected to is different than the local proxy.
|
||||
* <p>
|
||||
* This event corresponds to {@link com.velocitypowered.api.event.player.ServerConnectedEvent}, and is fired
|
||||
* asynchronously.
|
||||
*
|
||||
* @since 0.3.4
|
||||
*/
|
||||
public class PlayerChangedServerNetworkEvent implements IPlayerChangedServerNetworkEvent {
|
||||
private final UUID uuid;
|
||||
private final String previousServer;
|
||||
private final String server;
|
||||
|
||||
public PlayerChangedServerNetworkEvent(UUID uuid, String previousServer, String server) {
|
||||
this.uuid = uuid;
|
||||
this.previousServer = previousServer;
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUuid() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getServer() {
|
||||
return server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPreviousServer() {
|
||||
return previousServer;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.events;
|
||||
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPlayerJoinedNetworkEvent;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* This event is sent when a player joins the network. RedisBungee sends the event only when
|
||||
* the proxy the player has been connected to is different than the local proxy.
|
||||
* <p>
|
||||
* This event corresponds to {@link com.velocitypowered.api.event.connection.PostLoginEvent}, and is fired
|
||||
* asynchronously.
|
||||
*
|
||||
* @since 0.3.4
|
||||
*/
|
||||
public class PlayerJoinedNetworkEvent implements IPlayerJoinedNetworkEvent {
|
||||
private final UUID uuid;
|
||||
|
||||
public PlayerJoinedNetworkEvent(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUuid() {
|
||||
return uuid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.events;
|
||||
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPlayerLeftNetworkEvent;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* This event is sent when a player disconnects. RedisBungee sends the event only when
|
||||
* the proxy the player has been connected to is different than the local proxy.
|
||||
* <p>
|
||||
* This event corresponds to {@link com.velocitypowered.api.event.connection.DisconnectEvent}, and is fired
|
||||
* asynchronously.
|
||||
*
|
||||
* @since 0.3.4
|
||||
*/
|
||||
public class PlayerLeftNetworkEvent implements IPlayerLeftNetworkEvent {
|
||||
private final UUID uuid;
|
||||
|
||||
public PlayerLeftNetworkEvent(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUuid() {
|
||||
return uuid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright (c) 2013-present RedisBungee contributors
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
*
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
|
||||
package com.imaginarycode.minecraft.redisbungee.events;
|
||||
|
||||
|
||||
import com.imaginarycode.minecraft.redisbungee.api.events.IPubSubMessageEvent;
|
||||
|
||||
/**
|
||||
* This event is posted when a PubSub message is received.
|
||||
* <p>
|
||||
* <strong>Warning</strong>: This event is fired in a separate thread!
|
||||
*
|
||||
* @since 0.2.6
|
||||
*/
|
||||
|
||||
public class PubSubMessageEvent implements IPubSubMessageEvent {
|
||||
private final String channel;
|
||||
private final String message;
|
||||
|
||||
public PubSubMessageEvent(String channel, String message) {
|
||||
this.channel = channel;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getChannel() {
|
||||
return channel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
7
copyright_print.txt
Normal file
7
copyright_print.txt
Normal file
@@ -0,0 +1,7 @@
|
||||
Copyright (c) 2013-present RedisBungee contributors
|
||||
|
||||
All rights reserved. This program and the accompanying materials
|
||||
are made available under the terms of the Eclipse Public License v1.0
|
||||
which accompanies this distribution, and is available at
|
||||
|
||||
http://www.eclipse.org/legal/epl-v10.html
|
||||
0
gradle.build.kts
Normal file
0
gradle.build.kts
Normal file
2
gradle.properties
Normal file
2
gradle.properties
Normal file
@@ -0,0 +1,2 @@
|
||||
group = com.imaginarycode.minecraft
|
||||
version = 0.11.1-SNAPSHOT
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
6
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
6
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip
|
||||
networkTimeout=10000
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
244
gradlew
vendored
Executable file
244
gradlew
vendored
Executable file
@@ -0,0 +1,244 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
92
gradlew.bat
vendored
Normal file
92
gradlew.bat
vendored
Normal file
@@ -0,0 +1,92 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
2
jitpack.yml
Normal file
2
jitpack.yml
Normal file
@@ -0,0 +1,2 @@
|
||||
jdk:
|
||||
- openjdk11
|
||||
@@ -1,3 +0,0 @@
|
||||
rm -rf javadoc
|
||||
mkdir javadoc
|
||||
mvn javadoc:javadoc -pl RedisBungee-API,RedisBungee-BungeeEvents -am
|
||||
61
pom.xml
61
pom.xml
@@ -1,61 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.imaginarycode.minecraft</groupId>
|
||||
<artifactId>RedisBungee</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<version>0.7.3-SNAPSHOT</version>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>8</source>
|
||||
<target>8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<modules>
|
||||
<module>RedisBungee-API</module>
|
||||
<module>RedisBungee-Bungee</module>
|
||||
</modules>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>31.1-jre</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>redis.clients</groupId>
|
||||
<artifactId>jedis</artifactId>
|
||||
<version>4.2.3</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-pool2</artifactId>
|
||||
<version>2.11.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>2.7.5</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
11
settings.gradle.kts
Normal file
11
settings.gradle.kts
Normal file
@@ -0,0 +1,11 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "RedisBungee-Parent"
|
||||
|
||||
include(":RedisBungee-Velocity")
|
||||
include(":RedisBungee-Bungee")
|
||||
include(":RedisBungee-API")
|
||||
Reference in New Issue
Block a user