Initial sanctuary sources

This commit is contained in:
cnstiout
2026-07-04 20:27:08 +02:00
commit c796a20321
1582 changed files with 253264 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
# Gradle
.gradle/
build/
out/
classes/
# Eclipse
*.launch
# IntelliJ IDEA
.idea/
*.iml
*.ipr
*.iws
# VS Code
.settings/
.vscode/
bin/
.classpath
.project
# macOS
*.DS_Store
# Fabric
run/
# Java
.jdk/
hs_err_*.log
replay_*.log
*.hprof
*.jfr
# Local source assets
/sanctuary.png
+18
View File
@@ -0,0 +1,18 @@
# Sanctuary RPC
Client-only Fabric mod for Minecraft `26.1.2`. It publishes a Discord Rich Presence saying the player is playing Sanctuary.
## Setup
1. Build the mod with Java 25:
```sh
JAVA_HOME=$PWD/.jdk/current ./gradlew build
```
2. Copy `build/libs/sanctuary_rpc-1.0.0.jar` into the Fabric mods folder.
3. Launch Minecraft once. The mod creates `config/sanctuary-rpc.properties`.
4. Replace `clientId=put-your-discord-application-id-here` with the application ID from the Discord Developer Portal.
5. Optional: add a Rich Presence art asset named `sanctuary` in that Discord application, or change `largeImage` in the config.
Discord must be open on the same computer for IPC to connect.
+67
View File
@@ -0,0 +1,67 @@
plugins {
id "net.fabricmc.fabric-loom" version "${loom_version}"
id "maven-publish"
}
version = project.mod_version
group = project.maven_group
repositories {
}
loom {
splitEnvironmentSourceSets()
mods {
"sanctuary_rpc" {
sourceSet sourceSets.main
sourceSet sourceSets.client
}
}
}
dependencies {
minecraft "com.mojang:minecraft:${project.minecraft_version}"
implementation "net.fabricmc:fabric-loader:${project.loader_version}"
implementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_api_version}"
}
processResources {
def version = project.version
inputs.property "version", version
filesMatching("fabric.mod.json") {
expand "version": version
}
}
tasks.withType(JavaCompile).configureEach {
it.options.release = 25
}
java {
withSourcesJar()
sourceCompatibility = JavaVersion.VERSION_25
targetCompatibility = JavaVersion.VERSION_25
}
jar {
def projectName = project.name
inputs.property "projectName", projectName
from("../../license.txt") {
rename { "${it}_${projectName}" }
}
}
publishing {
publications {
create("mavenJava", MavenPublication) {
from components.java
}
}
repositories {
}
}
@@ -0,0 +1,21 @@
# Done to increase the memory available to Gradle.
org.gradle.jvmargs=-Xmx1G
org.gradle.parallel=true
# IntelliJ IDEA is not yet fully compatible with configuration cache:
# https://github.com/FabricMC/fabric-loom/issues/1349
org.gradle.configuration-cache=false
# Fabric properties
# Check current versions on https://fabricmc.net/develop
minecraft_version=26.1.2
loader_version=0.19.2
loom_version=1.16-SNAPSHOT
# Mod properties
mod_version=1.0.0
maven_group=fr.koka99cab
archives_base_name=sanctuary_rpc
# Dependencies
fabric_api_version=0.148.0+26.1.2
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+253
View File
@@ -0,0 +1,253 @@
#!/bin/sh
#
# Copyright © 2015 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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# 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/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/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##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
if [ -z "$JAVA_HOME" ] && [ -x "$APP_HOME/.jdk/current/bin/java" ] ; then
JAVA_HOME=$APP_HOME/.jdk/current
export JAVA_HOME
fi
# 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
# 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
if ! command -v java >/dev/null 2>&1
then
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
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=SC2039,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=SC2039,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" )
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
# 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"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# 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" "$@"
+93
View File
@@ -0,0 +1,93 @@
@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
@rem SPDX-License-Identifier: Apache-2.0
@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. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
: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
+12
View File
@@ -0,0 +1,12 @@
pluginManagement {
repositories {
maven {
name = "Fabric"
url = "https://maven.fabricmc.net/"
}
mavenCentral()
gradlePluginPortal()
}
}
rootProject.name = "sanctuary_rpc"
@@ -0,0 +1,41 @@
package fr.koka99cab.sanctuaryrpc.client;
import fr.koka99cab.sanctuaryrpc.SanctuaryRpcMod;
import fr.koka99cab.sanctuaryrpc.client.config.SanctuaryRpcConfig;
import fr.koka99cab.sanctuaryrpc.client.discord.DiscordActivity;
import fr.koka99cab.sanctuaryrpc.client.discord.DiscordIpcClient;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;
public class SanctuaryRpcClient implements ClientModInitializer {
private DiscordIpcClient discordIpcClient;
@Override
public void onInitializeClient() {
SanctuaryRpcConfig config = SanctuaryRpcConfig.load();
if (!config.enabled()) {
SanctuaryRpcMod.LOGGER.info("Discord RPC Sanctuary desactive dans la configuration.");
return;
}
if (!config.hasClientId()) {
SanctuaryRpcMod.LOGGER.warn(
"Sanctuary RPC attend un clientId Discord dans config/sanctuary-rpc.properties."
);
return;
}
discordIpcClient = new DiscordIpcClient(
config.clientId(),
DiscordActivity.fromConfig(config),
SanctuaryRpcMod.LOGGER
);
discordIpcClient.start();
ClientLifecycleEvents.CLIENT_STOPPING.register(client -> {
if (discordIpcClient != null) {
discordIpcClient.stop();
}
});
}
}
@@ -0,0 +1,115 @@
package fr.koka99cab.sanctuaryrpc.client.config;
import fr.koka99cab.sanctuaryrpc.SanctuaryRpcMod;
import net.fabricmc.loader.api.FabricLoader;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
public record SanctuaryRpcConfig(
boolean enabled,
String clientId,
String details,
String state,
String largeImage,
String largeText,
String smallImage,
String smallText,
boolean showElapsedTime
) {
private static final String CONFIG_FILE = "sanctuary-rpc.properties";
private static final String DEFAULT_CLIENT_ID = "1522671140735025182";
private static final String OLD_CLIENT_ID_PLACEHOLDER = "put-your-discord-application-id-here";
public static SanctuaryRpcConfig load() {
Path path = FabricLoader.getInstance().getConfigDir().resolve(CONFIG_FILE);
Properties properties = defaultProperties();
boolean shouldSave = false;
try {
if (Files.notExists(path)) {
writeDefaults(path, properties);
} else {
try (Reader reader = Files.newBufferedReader(path)) {
properties.load(reader);
}
shouldSave = migrate(properties);
}
} catch (IOException exception) {
SanctuaryRpcMod.LOGGER.warn("Impossible de lire la configuration Sanctuary RPC, valeurs par defaut utilisees.", exception);
}
if (shouldSave) {
try {
writeDefaults(path, properties);
} catch (IOException exception) {
SanctuaryRpcMod.LOGGER.warn("Impossible de mettre a jour la configuration Sanctuary RPC.", exception);
}
}
return new SanctuaryRpcConfig(
Boolean.parseBoolean(properties.getProperty("enabled")),
properties.getProperty("clientId", "").trim(),
properties.getProperty("details", "").trim(),
properties.getProperty("state", "").trim(),
properties.getProperty("largeImage", "").trim(),
properties.getProperty("largeText", "").trim(),
properties.getProperty("smallImage", "").trim(),
properties.getProperty("smallText", "").trim(),
Boolean.parseBoolean(properties.getProperty("showElapsedTime"))
);
}
public boolean hasClientId() {
return !clientId.isBlank();
}
private static Properties defaultProperties() {
Properties properties = new Properties();
properties.setProperty("enabled", "true");
properties.setProperty("clientId", DEFAULT_CLIENT_ID);
properties.setProperty("details", "Joue a Sanctuary");
properties.setProperty("state", "Minecraft 26.1.2 - Fabric");
properties.setProperty("largeImage", "");
properties.setProperty("largeText", "Sanctuary");
properties.setProperty("smallImage", "");
properties.setProperty("smallText", "");
properties.setProperty("showElapsedTime", "true");
return properties;
}
private static boolean migrate(Properties properties) {
boolean changed = false;
String clientId = properties.getProperty("clientId", "").trim();
if (clientId.isBlank() || OLD_CLIENT_ID_PLACEHOLDER.equals(clientId)) {
properties.setProperty("clientId", DEFAULT_CLIENT_ID);
changed = true;
}
for (String key : defaultProperties().stringPropertyNames()) {
if (!properties.containsKey(key)) {
properties.setProperty(key, defaultProperties().getProperty(key));
changed = true;
}
}
return changed;
}
private static void writeDefaults(Path path, Properties properties) throws IOException {
Files.createDirectories(path.getParent());
try (Writer writer = Files.newBufferedWriter(path)) {
writer.write("# Sanctuary RPC\n");
writer.write("# clientId doit etre l'identifiant d'une application Discord Developer Portal.\n");
writer.write("# Pour afficher une image, ajoute un asset Rich Presence nomme comme largeImage.\n");
properties.store(writer, null);
}
}
}
@@ -0,0 +1,60 @@
package fr.koka99cab.sanctuaryrpc.client.discord;
import com.google.gson.JsonObject;
import fr.koka99cab.sanctuaryrpc.client.config.SanctuaryRpcConfig;
import java.time.Instant;
public record DiscordActivity(
String details,
String state,
String largeImage,
String largeText,
String smallImage,
String smallText,
boolean showElapsedTime,
long startedAt
) {
public static DiscordActivity fromConfig(SanctuaryRpcConfig config) {
return new DiscordActivity(
config.details(),
config.state(),
config.largeImage(),
config.largeText(),
config.smallImage(),
config.smallText(),
config.showElapsedTime(),
Instant.now().getEpochSecond()
);
}
public JsonObject toJson() {
JsonObject activity = new JsonObject();
putIfNotBlank(activity, "details", details);
putIfNotBlank(activity, "state", state);
if (showElapsedTime) {
JsonObject timestamps = new JsonObject();
timestamps.addProperty("start", startedAt);
activity.add("timestamps", timestamps);
}
JsonObject assets = new JsonObject();
putIfNotBlank(assets, "large_image", largeImage);
putIfNotBlank(assets, "large_text", largeText);
putIfNotBlank(assets, "small_image", smallImage);
putIfNotBlank(assets, "small_text", smallText);
if (assets.size() > 0) {
activity.add("assets", assets);
}
return activity;
}
private static void putIfNotBlank(JsonObject json, String key, String value) {
if (value != null && !value.isBlank()) {
json.addProperty(key, value);
}
}
}
@@ -0,0 +1,243 @@
package fr.koka99cab.sanctuaryrpc.client.discord;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
public final class DiscordIpcClient {
private static final long RECONNECT_DELAY_MILLIS = 15_000L;
private static final long ACTIVITY_REFRESH_MILLIS = 30_000L;
private final String clientId;
private final DiscordActivity activity;
private final Logger logger;
private final AtomicBoolean running = new AtomicBoolean();
private volatile DiscordIpcConnection connection;
private volatile String lastActivityNonce;
private Thread worker;
private boolean missingDiscordLogged;
private boolean activityAcceptedLogged;
public DiscordIpcClient(String clientId, DiscordActivity activity, Logger logger) {
this.clientId = clientId;
this.activity = activity;
this.logger = logger;
}
public void start() {
if (!running.compareAndSet(false, true)) {
return;
}
worker = new Thread(this::run, "Sanctuary Discord RPC");
worker.setDaemon(true);
worker.start();
}
public void stop() {
if (!running.compareAndSet(true, false)) {
return;
}
DiscordIpcConnection activeConnection = connection;
if (activeConnection != null) {
try {
clearActivity(activeConnection);
} catch (IOException exception) {
logger.debug("Impossible d'effacer la presence Discord.", exception);
}
try {
activeConnection.close();
} catch (IOException exception) {
logger.debug("Impossible de fermer la connexion Discord IPC.", exception);
}
}
Thread activeWorker = worker;
if (activeWorker != null) {
activeWorker.interrupt();
}
}
private void run() {
while (running.get()) {
try (DiscordIpcConnection activeConnection = DiscordIpcConnection.open()) {
connection = activeConnection;
handshake(activeConnection);
setActivity(activeConnection);
missingDiscordLogged = false;
logger.info("Presence Discord Sanctuary active via {}.", activeConnection.endpoint());
AtomicBoolean refreshRunning = new AtomicBoolean(true);
Thread refreshWorker = startRefreshWorker(activeConnection, refreshRunning);
try {
readLoop(activeConnection);
} finally {
refreshRunning.set(false);
refreshWorker.interrupt();
}
} catch (IOException exception) {
logConnectionFailure(exception);
} finally {
connection = null;
}
sleepBeforeReconnect();
}
}
private void handshake(DiscordIpcConnection activeConnection) throws IOException {
JsonObject payload = new JsonObject();
payload.addProperty("v", 1);
payload.addProperty("client_id", clientId);
activeConnection.writeFrame(DiscordIpcConnection.OPCODE_HANDSHAKE, payload);
}
private void setActivity(DiscordIpcConnection activeConnection) throws IOException {
JsonObject args = new JsonObject();
args.addProperty("pid", ProcessHandle.current().pid());
args.add("activity", activity.toJson());
JsonObject payload = new JsonObject();
payload.addProperty("cmd", "SET_ACTIVITY");
payload.add("args", args);
String nonce = UUID.randomUUID().toString();
payload.addProperty("nonce", nonce);
lastActivityNonce = nonce;
activeConnection.writeFrame(DiscordIpcConnection.OPCODE_FRAME, payload);
}
private void clearActivity(DiscordIpcConnection activeConnection) throws IOException {
JsonObject args = new JsonObject();
args.addProperty("pid", ProcessHandle.current().pid());
args.add("activity", null);
JsonObject payload = new JsonObject();
payload.addProperty("cmd", "SET_ACTIVITY");
payload.add("args", args);
payload.addProperty("nonce", UUID.randomUUID().toString());
activeConnection.writeFrame(DiscordIpcConnection.OPCODE_FRAME, payload);
}
private void readLoop(DiscordIpcConnection activeConnection) throws IOException {
while (running.get()) {
DiscordIpcConnection.IpcFrame frame = activeConnection.readFrame();
if (frame == null || frame.opcode() == DiscordIpcConnection.OPCODE_CLOSE) {
return;
}
if (frame.opcode() == DiscordIpcConnection.OPCODE_PING) {
activeConnection.writeFrame(DiscordIpcConnection.OPCODE_PONG, frame.payload());
continue;
}
if (frame.opcode() == DiscordIpcConnection.OPCODE_FRAME) {
handlePayload(frame.payload());
}
}
}
private Thread startRefreshWorker(DiscordIpcConnection activeConnection, AtomicBoolean refreshRunning) {
Thread refreshWorker = new Thread(() -> {
while (running.get() && refreshRunning.get()) {
try {
Thread.sleep(ACTIVITY_REFRESH_MILLIS);
if (running.get() && refreshRunning.get()) {
setActivity(activeConnection);
}
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
} catch (IOException exception) {
logger.debug("Impossible de rafraichir la presence Discord.", exception);
refreshRunning.set(false);
}
}
}, "Sanctuary Discord RPC refresh");
refreshWorker.setDaemon(true);
refreshWorker.start();
return refreshWorker;
}
private void handlePayload(String payload) {
try {
JsonObject json = JsonParser.parseString(payload).getAsJsonObject();
String command = stringMember(json, "cmd");
String event = stringMember(json, "evt");
String nonce = stringMember(json, "nonce");
if ("ERROR".equals(command)) {
JsonObject data = objectMember(json, "data");
String message = data == null ? payload : stringMember(data, "message");
logger.warn("Discord RPC a renvoye une erreur: {}", message == null ? payload : message);
} else if ("DISPATCH".equals(command) && "READY".equals(event)) {
logger.debug("Discord RPC pret.");
} else if ("SET_ACTIVITY".equals(command) && nonce != null && nonce.equals(lastActivityNonce)) {
logActivityAccepted(json);
}
} catch (RuntimeException exception) {
logger.debug("Payload Discord RPC ignore.", exception);
}
}
private void logActivityAccepted(JsonObject payload) {
if (activityAcceptedLogged) {
logger.debug("Discord RPC confirme le rafraichissement de l'activite.");
return;
}
JsonObject data = objectMember(payload, "data");
String name = data == null ? null : stringMember(data, "name");
String details = data == null ? null : stringMember(data, "details");
String state = data == null ? null : stringMember(data, "state");
logger.info(
"Discord RPC confirme l'activite: name={}, details={}, state={}.",
name == null ? "?" : name,
details == null ? "?" : details,
state == null ? "?" : state
);
activityAcceptedLogged = true;
}
private void logConnectionFailure(IOException exception) {
if (!running.get()) {
return;
}
if (!missingDiscordLogged) {
logger.warn(exception.getMessage());
missingDiscordLogged = true;
} else {
logger.debug("Reconnexion Discord RPC en attente.", exception);
}
}
private void sleepBeforeReconnect() {
if (!running.get()) {
return;
}
try {
Thread.sleep(RECONNECT_DELAY_MILLIS);
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
}
}
private static JsonObject objectMember(JsonObject json, String memberName) {
JsonElement element = json.get(memberName);
return element != null && element.isJsonObject() ? element.getAsJsonObject() : null;
}
private static String stringMember(JsonObject json, String memberName) {
JsonElement element = json.get(memberName);
return element != null && element.isJsonPrimitive() ? element.getAsString() : null;
}
}
@@ -0,0 +1,208 @@
package fr.koka99cab.sanctuaryrpc.client.discord;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.Closeable;
import java.io.IOException;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.ByteChannel;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
final class DiscordIpcConnection implements Closeable {
static final int OPCODE_HANDSHAKE = 0;
static final int OPCODE_FRAME = 1;
static final int OPCODE_CLOSE = 2;
static final int OPCODE_PING = 3;
static final int OPCODE_PONG = 4;
private static final Gson GSON = new Gson();
private static final int MAX_FRAME_SIZE = 1024 * 1024;
private final ByteChannel channel;
private final String endpoint;
private DiscordIpcConnection(ByteChannel channel, String endpoint) {
this.channel = channel;
this.endpoint = endpoint;
}
static DiscordIpcConnection open() throws IOException {
if (isWindows()) {
return openWindowsPipe();
}
return openUnixSocket();
}
synchronized void writeFrame(int opcode, JsonObject payload) throws IOException {
writeFrame(opcode, GSON.toJson(payload));
}
synchronized void writeFrame(int opcode, String payload) throws IOException {
byte[] payloadBytes = payload.getBytes(StandardCharsets.UTF_8);
ByteBuffer buffer = ByteBuffer.allocate(8 + payloadBytes.length).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(opcode);
buffer.putInt(payloadBytes.length);
buffer.put(payloadBytes);
buffer.flip();
writeFully(buffer);
}
IpcFrame readFrame() throws IOException {
ByteBuffer header = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
if (!readFully(header)) {
return null;
}
header.flip();
int opcode = header.getInt();
int length = header.getInt();
if (length < 0 || length > MAX_FRAME_SIZE) {
throw new IOException("Discord IPC frame invalide: " + length + " octets.");
}
ByteBuffer payload = ByteBuffer.allocate(length);
if (!readFully(payload)) {
return null;
}
payload.flip();
return new IpcFrame(opcode, StandardCharsets.UTF_8.decode(payload).toString());
}
String endpoint() {
return endpoint;
}
@Override
public void close() throws IOException {
channel.close();
}
private void writeFully(ByteBuffer buffer) throws IOException {
while (buffer.hasRemaining()) {
int written = channel.write(buffer);
if (written == 0) {
Thread.onSpinWait();
}
}
}
private boolean readFully(ByteBuffer buffer) throws IOException {
while (buffer.hasRemaining()) {
int read = channel.read(buffer);
if (read < 0) {
return false;
}
if (read == 0) {
Thread.onSpinWait();
}
}
return true;
}
private static DiscordIpcConnection openUnixSocket() throws IOException {
IOException lastException = null;
for (Path candidate : unixCandidates()) {
if (!Files.exists(candidate)) {
continue;
}
SocketChannel socket = null;
try {
socket = SocketChannel.open(StandardProtocolFamily.UNIX);
socket.connect(UnixDomainSocketAddress.of(candidate));
return new DiscordIpcConnection(socket, candidate.toString());
} catch (IOException exception) {
lastException = exception;
if (socket != null) {
socket.close();
}
}
}
throw missingDiscordException(lastException);
}
private static DiscordIpcConnection openWindowsPipe() throws IOException {
IOException lastException = null;
for (int index = 0; index < 10; index++) {
String endpoint = "\\\\.\\pipe\\discord-ipc-" + index;
try {
FileChannel channel = FileChannel.open(
Path.of(endpoint),
StandardOpenOption.READ,
StandardOpenOption.WRITE
);
return new DiscordIpcConnection(channel, endpoint);
} catch (IOException exception) {
lastException = exception;
}
}
throw missingDiscordException(lastException);
}
private static List<Path> unixCandidates() {
List<Path> candidates = new ArrayList<>();
for (Path runtimeDirectory : unixRuntimeDirectories()) {
for (int index = 0; index < 10; index++) {
candidates.add(runtimeDirectory.resolve("discord-ipc-" + index));
candidates.add(runtimeDirectory.resolve("snap.discord/discord-ipc-" + index));
candidates.add(runtimeDirectory.resolve("app/com.discordapp.Discord/discord-ipc-" + index));
}
}
return candidates;
}
private static Set<Path> unixRuntimeDirectories() {
Set<Path> directories = new LinkedHashSet<>();
addEnvironmentPath(directories, "XDG_RUNTIME_DIR");
addEnvironmentPath(directories, "TMPDIR");
addEnvironmentPath(directories, "TMP");
addEnvironmentPath(directories, "TEMP");
directories.add(Path.of("/tmp"));
return directories;
}
private static void addEnvironmentPath(Set<Path> directories, String name) {
String value = System.getenv(name);
if (value != null && !value.isBlank()) {
directories.add(Path.of(value));
}
}
private static boolean isWindows() {
return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win");
}
private static IOException missingDiscordException(IOException cause) {
IOException exception = new IOException("Aucune connexion Discord IPC trouvee. Lance Discord puis redemarre Minecraft.");
if (cause != null) {
exception.initCause(cause);
}
return exception;
}
record IpcFrame(int opcode, String payload) {
}
}
@@ -0,0 +1,15 @@
package fr.koka99cab.sanctuaryrpc;
import net.fabricmc.api.ModInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SanctuaryRpcMod implements ModInitializer {
public static final String MOD_ID = "sanctuary_rpc";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
@Override
public void onInitialize() {
LOGGER.info("Sanctuary RPC initialise.");
}
}
@@ -0,0 +1,3 @@
{
"modmenu.descriptionTranslation.sanctuary_rpc": "Shows a Discord Rich Presence while playing Sanctuary."
}
@@ -0,0 +1,3 @@
{
"modmenu.descriptionTranslation.sanctuary_rpc": "Affiche une presence Discord Rich Presence pendant une partie Sanctuary."
}
@@ -0,0 +1,26 @@
{
"schemaVersion": 1,
"id": "sanctuary_rpc",
"version": "${version}",
"name": "Sanctuary RPC",
"description": "Discord Rich Presence client mod for showing that you are playing Sanctuary.",
"authors": [
"KOKA99CAB"
],
"license": "LGPL-3.0-or-later",
"environment": "client",
"entrypoints": {
"main": [
"fr.koka99cab.sanctuaryrpc.SanctuaryRpcMod"
],
"client": [
"fr.koka99cab.sanctuaryrpc.client.SanctuaryRpcClient"
]
},
"depends": {
"fabricloader": ">=0.19.2",
"minecraft": "~26.1.2",
"java": ">=25",
"fabric-api": "*"
}
}