Skip to content

Commit

Permalink
Fixed :D
Browse files Browse the repository at this point in the history
  • Loading branch information
AnyBananaGAME committed Dec 25, 2024
1 parent dd721f9 commit 2ce6ee5
Show file tree
Hide file tree
Showing 11 changed files with 102 additions and 98 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
node_modules/
dist/
package-lock.json
cache/
tokens/
.vscode/
dev/
Expand All @@ -12,4 +13,5 @@ src/tools/level
src/history/
note.txt
bun.lockb
src/tools/z.ts
src/tools/z.ts
src/tools/rat.ts
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ npm i @sanctumterra/client
| 2.0.10 | 712 | 1.21.20 |
| 2.1.5 | 729 | 1.21.30 |
| 2.1.12 | 748 | 1.21.40 |
| 2.1.13 | 766 | 1.21.50 |
| 2.1.16 | 766 | 1.21.50 |

## 🚀 Usage Example

Expand All @@ -44,7 +44,10 @@ const client = new Client({
username: "SanctumTerra",
tokensFolder: "./cache/tokens",
version: "1.21.50",
deviceOS: DeviceOS.Android
deviceOS: DeviceOS.Android,
sendAuthInput: true,
logPacketErrors: false,
tickRate: 50 // 50 is the default tick rate
});

client.connect();
Expand Down Expand Up @@ -76,7 +79,8 @@ client.on("spawn", () => {

### 🎛️ Client Configuration
- **Required Parameters**: `host`, `port`
- **Optional Parameters**: `offline`, `username`, `tokensFolder`, `version`, `deviceOS`, `viewDistance`
- **Optional Parameters**:
`offline`, `username`, `tokensFolder`, `version`, `deviceOS`, `viewDistance`, `sendAuthInput`, `logPacketErrors`, `tickRate`

### 📡 Event Handling
- Events allow you to listen to any implemented packet if it is not implemented you will receive a warning and it should not crash if there is a crash then make an issue on github.
Expand All @@ -88,6 +92,11 @@ client.on("spawn", () => {

## 📜 Changelog

### 2.1.16
- Fixed bugs with BDS.
- Added more options.
- New Listener Events.

### 2.1.14
- Use latest version of Raknet
- Fixes
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"name": "@sanctumterra/client",
"version": "2.1.15",
"version": "2.1.16",
"minecraft": "1.21.50",
"description": "We'll be singing Baraye.",
"description": "MCBE Client",
"main": "./dist/index.js",
"type": "commonjs",
"scripts": {
Expand Down Expand Up @@ -38,6 +38,7 @@
"@sanctumterra/raknet": "^1.3.67",
"@serenityjs/binarystream": "^2.6.6",
"@serenityjs/block": "^0.4.4",
"@serenityjs/emitter": "^0.6.4",
"@serenityjs/network": "^0.4.4",
"@serenityjs/protocol": "^0.6.4-beta-20241210051348",
"@serenityjs/raknet": "^0.6.2-beta-20241128210118",
Expand Down
37 changes: 20 additions & 17 deletions src/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,7 @@ import {
AnimateId,
ComplexInventoryTransaction,
BlockPosition,
ItemStackRequestPacket,
ItemStackRequestActionType,
ItemStackRequest,
ItemStackRequestAction,
ItemStackActionTakePlace,
type DisconnectPacket,
} from "@serenityjs/protocol";
import { Priority } from "@serenityjs/raknet";
import type { ClientOptions } from "./client/ClientOptions";
Expand Down Expand Up @@ -58,6 +54,8 @@ class Client extends Connection {
private isBreaking = false;
private requestId = -2;

private _authInputInterval!: NodeJS.Timeout;

constructor(options: Partial<ClientOptions> = {}) {
super(options);
this.inventory = new Inventory(this);
Expand All @@ -79,8 +77,19 @@ class Client extends Connection {
}
}

public disconnect(
clientSide?: boolean,
packet?: DisconnectPacket | null,
): void {
clearInterval(this._authInputInterval);
super.disconnect(clientSide, packet);
}

private handleAuthInput(): void {
setInterval(() => {
this._authInputInterval = setInterval(() => {
// So people can switch it live.
if (!this.options.sendAuthInput) return;

const inputData = new PlayerAuthInputData(0n);
inputData.setFlag(InputData.BlockBreakingDelayEnabled, true);
if (this.sneaking) {
Expand Down Expand Up @@ -110,12 +119,9 @@ class Client extends Connection {
packet.analogueMotion = new Vector2f(0, 0);
packet.cameraOrientation = new Vector3f(0, 0, 0);
packet.rawMoveVector = new Vector2f(0, 0);
const cancel = false;
this.emit("PrePlayerAuthInputPacket", packet, cancel);
if (!cancel) {
this.sendPacket(packet, Priority.Immediate);
}
}, 50);
this.emit("PrePlayerAuthInputPacket", packet);
this.sendPacket(packet, Priority.Normal);
}, 100);
}

public sendMessage(text: string): void {
Expand Down Expand Up @@ -243,12 +249,9 @@ class Client extends Connection {
modifier: (packet: CustomPlayerAuthInputPacket) => void,
): Promise<void> => {
return new Promise((resolve) => {
const handler = (
packet: ProtocolPlayerAuthInputPacket,
cancel: boolean,
) => {
const handler = (packet: ProtocolPlayerAuthInputPacket) => {
modifier(packet as unknown as CustomPlayerAuthInputPacket);
this.removeListener("PrePlayerAuthInputPacket", handler);
this.remove("PrePlayerAuthInputPacket", handler);
resolve();
};
this.on("PrePlayerAuthInputPacket", handler);
Expand Down
39 changes: 31 additions & 8 deletions src/Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import {
ResourcePackResponse,
type ResourcePacksInfoPacket,
ResourcePackStackPacket,
ServerboundLoadingScreenPacketPacket,
ServerboundLoadingScreenType,
type ServerToClientHandshakePacket,
SetLocalPlayerAsInitializedPacket,
type StartGamePacket,
Expand Down Expand Up @@ -96,6 +98,7 @@ class Connection extends Listener {

public disconnect(clientSide = true, packet: DisconnectPacket | null = null) {
const reason = packet?.message?.message ?? "Raknet Closed.";

Logger.info(`Disconnecting: ${reason}`);
if (clientSide) {
const disconnectPacket = new DisconnectPacket();
Expand All @@ -105,7 +108,7 @@ class Connection extends Listener {
this.sendPacket(disconnectPacket, Priority.Immediate);
}
clearInterval(this.ticker);
this.removeAllListeners();
this.removeAll();
// this.raknet.close();
}

Expand All @@ -115,6 +118,7 @@ class Connection extends Listener {
priority: Priority = Priority.Normal,
): void {
const packetId = packet.getId();
console.log(packetId);
const hexId = packetId.toString(16).padStart(2, "0");
if (this.options.debug) {
Logger.debug(
Expand All @@ -133,7 +137,7 @@ class Connection extends Listener {
this.raknet.once("connect", this.handleConnect.bind(this));
this.ticker = setInterval(() => {
this.emit("tick", this.tick++);
}, 50);
}, this.options.tickRate);
this.once("close", () => {
this.disconnect(false);
});
Expand All @@ -160,16 +164,29 @@ class Connection extends Listener {
private async initializeSession(): Promise<[Advertisement, StartGamePacket]> {
return new Promise((resolve, reject) => {
let Advertisement_: Advertisement;
this.onceAfter("StartGamePacket", (packet: StartGamePacket) => {
startGamePacket = packet;
});

this.once("session", async () => {
Advertisement_ = await this.handleSessionStart();
console.timeEnd("RakConnect");
});
let startGamePacket: StartGamePacket;
this.once("StartGamePacket", (packet: StartGamePacket) => {
startGamePacket = packet;
this.once("spawn", () => {
resolve([Advertisement_, startGamePacket]);
});

this.once("spawn", () => {
try {
if (startGamePacket) {
resolve([Advertisement_, startGamePacket]);
} else {
this.once("StartGamePacket", (packet: StartGamePacket) => {
startGamePacket = packet;
resolve([Advertisement_, startGamePacket]);
});
}
} catch (e) {
console.log(e);
}
});
this.options.offline ? createOfflineSession(this) : authenticate(this);
});
Expand Down Expand Up @@ -237,6 +254,12 @@ class Connection extends Listener {
if (instance.status === PlayStatus.PlayerSpawn) {
const init = new SetLocalPlayerAsInitializedPacket();
init.runtimeEntityId = this.runtimeEntityId;
const ServerBoundLoadingScreen =
new ServerboundLoadingScreenPacketPacket();
ServerBoundLoadingScreen.type =
ServerboundLoadingScreenType.EndLoadingScreen;
ServerBoundLoadingScreen.hasScreenId = false;
// this.sendPacket(ServerBoundLoadingScreen, Priority.Immediate);
this.sendPacket(init, Priority.Immediate);
this.emit("spawn");
}
Expand Down Expand Up @@ -313,7 +336,7 @@ class Connection extends Listener {
return ecdh.computeSecret(publicKeyBuffer);
} catch (error) {
Logger.error("Error computing shared secret:", error as Error);
throw new Error("Failed to create shared secret."); // More general error message
throw new Error("Failed to create shared secret.");
}
}

Expand Down
6 changes: 6 additions & 0 deletions src/client/ClientOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ type ClientOptions = {
tokensFolder: string;
viewDistance: number;
deviceOS: DeviceOS;
sendAuthInput: boolean;
logPacketErrors: boolean;
tickRate: number;
};

const defaultOptions: ClientOptions = {
Expand All @@ -55,6 +58,9 @@ const defaultOptions: ClientOptions = {
tokensFolder: `${process.cwd()}/tokens`,
viewDistance: 4,
deviceOS: DeviceOS.Win10,
sendAuthInput: true,
logPacketErrors: false,
tickRate: 50,
};

export {
Expand Down
48 changes: 9 additions & 39 deletions src/client/Listener.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,21 @@
import { EventEmitter } from "node:events";
import type * as Protocol from "@serenityjs/protocol";
import type { NetworkEvents } from "@serenityjs/network";

class Listener extends EventEmitter {
emit<K extends keyof ListenerEvents>(
eventName: K,
...args: Parameters<ListenerEvents[K]>
): boolean;
emit(eventName: string, ...args: unknown[]): boolean;
emit(eventName: string, ...args: unknown[]): boolean {
return super.emit(eventName, ...args);
}

on<K extends keyof ListenerEvents>(
eventName: K,
listener: ListenerEvents[K],
): this;
on(eventName: string, listener: (...args: unknown[]) => void): this;
on(eventName: string, listener: (...args: unknown[]) => void): this {
return super.on(eventName, listener);
}

once<K extends keyof ListenerEvents>(
eventName: K,
listener: ListenerEvents[K],
): this;
once(eventName: string, listener: (...args: unknown[]) => void): this;
once(eventName: string, listener: (...args: unknown[]) => void): this {
return super.once(eventName, listener);
}
}
import Emitter from "@serenityjs/emitter";

type PacketNames = {
[K in keyof typeof Protocol]: K extends `${string}Packet` ? K : never;
}[keyof typeof Protocol];

type ListenerEvents = {
// @ts-expect-error does not matter
[K in PacketNames]: (packet: InstanceType<(typeof Protocol)[K]>) => void;
[K in PacketNames]: [InstanceType<(typeof Protocol)[K]>];
} & {
session: () => void;
spawn: () => void;
tick: (tick: number) => void;
PrePlayerAuthInputPacket: (
packet: Protocol.PlayerAuthInputPacket,
cancel: boolean,
) => void;
session: [];
spawn: [];
tick: [number];
PrePlayerAuthInputPacket: [Protocol.PlayerAuthInputPacket];
close: [];
};

class Listener extends Emitter<ListenerEvents> {}

export { Listener, type ListenerEvents };
12 changes: 0 additions & 12 deletions src/tools/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,18 +143,6 @@ client.on("UpdateBlockPacket", (packet) => {
}
});

// process.on("uncaughtException", (error) => {
// writeToLog(
// `[UNCAUGHT EXCEPTION] ${sanitizeToLatin(error.message)}\n${sanitizeToLatin(error.stack || "")}`,
// );
// });

// process.on("unhandledRejection", (reason, promise) => {
// writeToLog(
// `[UNHANDLED REJECTION] at: ${sanitizeToLatin(String(promise))}\nReason: ${sanitizeToLatin(String(reason))}`,
// );
// });

client.on("TextPacket", handleTextPacket);

async function handleTextPacket(packet: TextPacket): Promise<void> {
Expand Down
Loading

0 comments on commit 2ce6ee5

Please sign in to comment.