Compare commits
1 Commits
main
...
73db39c8b2
Author | SHA1 | Date | |
---|---|---|---|
73db39c8b2
|
5
.github/workflows/build.yaml
vendored
5
.github/workflows/build.yaml
vendored
@@ -38,12 +38,13 @@ jobs:
|
|||||||
~/.cargo/registry/cache/
|
~/.cargo/registry/cache/
|
||||||
~/.cargo/git/db/
|
~/.cargo/git/db/
|
||||||
target/
|
target/
|
||||||
key: build_${{ matrix.os }}_${{ matrix.feature.name }}_${{ hashFiles('**.toml', 'Cargo.*') }}
|
key: build-${{ matrix.os }}-${{ matrix.feature.name }}-${{ hashFiles('**.toml', 'Cargo.*') }}
|
||||||
|
|
||||||
- name: Switch to nightly toolchain
|
- name: Switch to nightly toolchain
|
||||||
run: rustup default nightly
|
run: rustup default nightly
|
||||||
|
|
||||||
- run: cargo build --release ${{ matrix.feature.flags }}
|
- name: Build in release mode
|
||||||
|
run: cargo build --release ${{ matrix.feature.flags }}
|
||||||
|
|
||||||
- name: Upload build artifacts
|
- name: Upload build artifacts
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
|
10
.github/workflows/lint.yaml
vendored
10
.github/workflows/lint.yaml
vendored
@@ -36,7 +36,7 @@ jobs:
|
|||||||
feature:
|
feature:
|
||||||
- name: default
|
- name: default
|
||||||
|
|
||||||
- name: minimal+mimalloc
|
- name: minimal-mimalloc
|
||||||
flags: "--no-default-features -F mimalloc"
|
flags: "--no-default-features -F mimalloc"
|
||||||
|
|
||||||
- name: minimal
|
- name: minimal
|
||||||
@@ -61,7 +61,7 @@ jobs:
|
|||||||
~/.cargo/registry/cache/
|
~/.cargo/registry/cache/
|
||||||
~/.cargo/git/db/
|
~/.cargo/git/db/
|
||||||
target/
|
target/
|
||||||
key: lint_${{ matrix.feature.name }}_${{ hashFiles('**.toml', 'Cargo.*') }}
|
key: build-${{ matrix.os }}-${{ matrix.feature.name }}-${{ hashFiles('**.toml', 'Cargo.*') }}
|
||||||
|
|
||||||
- name: Switch to nightly toolchain
|
- name: Switch to nightly toolchain
|
||||||
run: rustup default nightly
|
run: rustup default nightly
|
||||||
@@ -69,7 +69,9 @@ jobs:
|
|||||||
- name: Install components
|
- name: Install components
|
||||||
run: rustup component add clippy rustfmt
|
run: rustup component add clippy rustfmt
|
||||||
|
|
||||||
- run: cargo clippy ${{ matrix.feature.flags }} -- -D warnings -D clippy::pedantic
|
- name: cargo clippy ${{ matrix.feature.flags }}
|
||||||
|
run: cargo clippy ${{ matrix.feature.flags }} -- -D warnings -D clippy::pedantic
|
||||||
|
|
||||||
- if: always()
|
- name: cargo fmt
|
||||||
|
if: always()
|
||||||
run: cargo fmt --check
|
run: cargo fmt --check
|
||||||
|
1222
Cargo.lock
generated
1222
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
16
Cargo.toml
16
Cargo.toml
@@ -21,31 +21,31 @@ built = { git = "https://github.com/lukaslueg/built", features = ["git2"] }
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
azalea = { git = "https://github.com/azalea-rs/azalea" }
|
azalea = { git = "https://github.com/azalea-rs/azalea" }
|
||||||
|
azalea-hax = { git = "https://github.com/azalea-rs/azalea-hax" }
|
||||||
bevy_app = "0"
|
bevy_app = "0"
|
||||||
bevy_ecs = "0"
|
bevy_ecs = "0"
|
||||||
bevy_log = "0"
|
bevy_log = "0"
|
||||||
clap = { version = "4", features = ["derive", "string"] }
|
clap = { version = "4", features = ["derive", "string"] }
|
||||||
console-subscriber = { version = "0", optional = true }
|
console-subscriber = { version = "0", optional = true }
|
||||||
ctrlc = "3"
|
ctrlc = { version = "3", features = ["termination"] }
|
||||||
dirs = { version = "6", optional = true }
|
dirs = "6"
|
||||||
futures = "0"
|
futures = "0"
|
||||||
futures-locks = "0"
|
futures-locks = "0"
|
||||||
http-body-util = "0"
|
http-body-util = "0"
|
||||||
hyper = { version = "1", features = ["server"] }
|
hyper = { version = "1", features = ["server"] }
|
||||||
hyper-util = "0"
|
hyper-util = "0"
|
||||||
log = "0"
|
log = { version = "0" }
|
||||||
matrix-sdk = { version = "0", features = ["anyhow"], optional = true }
|
matrix-sdk = { version = "0", optional = true }
|
||||||
mimalloc = { version = "0", optional = true }
|
mimalloc = { version = "0", optional = true }
|
||||||
mlua = { version = "0", features = ["async", "luajit", "send"] }
|
mlua = { version = "0", features = ["async", "luajit", "send"] }
|
||||||
ncr = { version = "0", features = ["cfb8", "ecb", "gcm"] }
|
ncr = { version = "0", features = ["cfb8", "ecb", "gcm"] }
|
||||||
parking_lot = "0"
|
parking_lot = "0"
|
||||||
serde = "1"
|
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["macros"] }
|
||||||
zip = { version = "2", default-features = false, features = ["flate2"] }
|
zip = { version = "2", default-features = false, features = ["flate2"] }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
console-subscriber = ["dep:console-subscriber"]
|
|
||||||
default = ["matrix"]
|
default = ["matrix"]
|
||||||
matrix = ["dep:dirs", "dep:matrix-sdk"]
|
console-subscriber = ["dep:console-subscriber"]
|
||||||
mimalloc = ["dep:mimalloc"]
|
mimalloc = ["dep:mimalloc"]
|
||||||
|
matrix = ["dep:matrix-sdk"]
|
||||||
|
@@ -5,6 +5,7 @@ A Minecraft bot with Lua scripting support, written in Rust with [azalea](https:
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Running Lua from
|
- Running Lua from
|
||||||
|
- `errornowatcher.lua`
|
||||||
- in-game chat messages
|
- in-game chat messages
|
||||||
- Matrix chat messages
|
- Matrix chat messages
|
||||||
- POST requests to HTTP server
|
- POST requests to HTTP server
|
||||||
@@ -13,7 +14,7 @@ A Minecraft bot with Lua scripting support, written in Rust with [azalea](https:
|
|||||||
- Entity and chest interaction
|
- Entity and chest interaction
|
||||||
- NoChatReports encryption
|
- NoChatReports encryption
|
||||||
- Saving ReplayMod recordings
|
- Saving ReplayMod recordings
|
||||||
- Matrix integration (w/ E2EE)
|
- Matrix integration
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
@@ -24,4 +25,4 @@ $ cargo build --release
|
|||||||
$ # ./target/release/errornowatcher
|
$ # ./target/release/errornowatcher
|
||||||
```
|
```
|
||||||
|
|
||||||
Make sure the `Server` and `Username` globals are defined in `main.lua` before starting the bot.
|
Make sure the `Server` and `Username` globals are defined in `errornowatcher.lua` before starting the bot.
|
||||||
|
@@ -2,7 +2,7 @@ Server = "localhost"
|
|||||||
Username = "ErrorNoWatcher"
|
Username = "ErrorNoWatcher"
|
||||||
HttpAddress = "127.0.0.1:8080"
|
HttpAddress = "127.0.0.1:8080"
|
||||||
Owners = { "ErrorNoInternet" }
|
Owners = { "ErrorNoInternet" }
|
||||||
MatrixOptions = { owners = { "@errornointernet:envs.net" } }
|
MatrixOwners = { "@errornointernet:envs.net" }
|
||||||
|
|
||||||
for _, module in ipairs({
|
for _, module in ipairs({
|
||||||
"lib",
|
"lib",
|
@@ -111,10 +111,6 @@ function attack_entities(target_kind, minimum)
|
|||||||
end
|
end
|
||||||
|
|
||||||
function check_food(hunger)
|
function check_food(hunger)
|
||||||
if not hunger then
|
|
||||||
hunger = client.hunger
|
|
||||||
end
|
|
||||||
|
|
||||||
if hunger.food >= 20 then
|
if hunger.food >= 20 then
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
|
@@ -63,7 +63,7 @@ function update_listeners()
|
|||||||
end,
|
end,
|
||||||
eat = function()
|
eat = function()
|
||||||
sleep(5000)
|
sleep(5000)
|
||||||
check_food()
|
check_food(client.hunger)
|
||||||
end,
|
end,
|
||||||
},
|
},
|
||||||
death = {
|
death = {
|
||||||
|
@@ -35,6 +35,9 @@ end
|
|||||||
function steal(item_name)
|
function steal(item_name)
|
||||||
for _, chest_pos in ipairs(client:find_blocks(client.position, get_block_states({ "chest" }))) do
|
for _, chest_pos in ipairs(client:find_blocks(client.position, get_block_states({ "chest" }))) do
|
||||||
client:go_to({ position = chest_pos, radius = 3 }, { type = RADIUS_GOAL })
|
client:go_to({ position = chest_pos, radius = 3 }, { type = RADIUS_GOAL })
|
||||||
|
while client.pathfinder.is_calculating or client.pathfinder.is_executing do
|
||||||
|
sleep(500)
|
||||||
|
end
|
||||||
client:look_at(chest_pos)
|
client:look_at(chest_pos)
|
||||||
|
|
||||||
local container = client:open_container_at(chest_pos)
|
local container = client:open_container_at(chest_pos)
|
||||||
|
@@ -93,6 +93,9 @@ function nether_travel(pos, go_to_opts)
|
|||||||
|
|
||||||
info(string.format("currently in nether, going to %.2f %.2f", nether_pos.x, nether_pos.z))
|
info(string.format("currently in nether, going to %.2f %.2f", nether_pos.x, nether_pos.z))
|
||||||
client:go_to(nether_pos, { type = XZ_GOAL })
|
client:go_to(nether_pos, { type = XZ_GOAL })
|
||||||
|
while client.pathfinder.is_calculating or client.pathfinder.is_executing do
|
||||||
|
sleep(1000)
|
||||||
|
end
|
||||||
|
|
||||||
info("arrived, looking for nearest portal")
|
info("arrived, looking for nearest portal")
|
||||||
local portals_nether = client:find_blocks(client.position, portal_block_states)
|
local portals_nether = client:find_blocks(client.position, portal_block_states)
|
||||||
@@ -141,6 +144,10 @@ function interact_bed()
|
|||||||
end
|
end
|
||||||
|
|
||||||
client:go_to({ position = bed, radius = 2 }, { type = RADIUS_GOAL, options = { without_mining = true } })
|
client:go_to({ position = bed, radius = 2 }, { type = RADIUS_GOAL, options = { without_mining = true } })
|
||||||
|
while client.pathfinder.is_calculating or client.pathfinder.is_executing do
|
||||||
|
sleep(500)
|
||||||
|
end
|
||||||
|
|
||||||
client:look_at(bed)
|
client:look_at(bed)
|
||||||
client:block_interact(bed)
|
client:block_interact(bed)
|
||||||
end
|
end
|
||||||
|
@@ -1,2 +0,0 @@
|
|||||||
[toolchain]
|
|
||||||
channel = "nightly"
|
|
@@ -1 +0,0 @@
|
|||||||
group_imports = "StdExternalCrate"
|
|
@@ -1,18 +1,16 @@
|
|||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use clap::Parser;
|
|
||||||
|
|
||||||
use crate::build_info;
|
use crate::build_info;
|
||||||
|
use clap::Parser;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
/// A Minecraft bot with Lua scripting support
|
/// A Minecraft bot with Lua scripting support
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[command(version = build_info::version_formatted())]
|
#[command(version = build_info::version_formatted())]
|
||||||
pub struct Arguments {
|
pub struct Arguments {
|
||||||
/// Path to main Lua file
|
/// Path to Lua entry point
|
||||||
#[arg(short, long)]
|
#[arg(short, long, default_value = "errornowatcher.lua")]
|
||||||
pub script: Option<PathBuf>,
|
pub script: PathBuf,
|
||||||
|
|
||||||
/// Code to execute (after script)
|
/// Code to execute after loading script
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
pub exec: Option<String>,
|
pub exec: Option<String>,
|
||||||
}
|
}
|
||||||
|
@@ -1,16 +1,11 @@
|
|||||||
|
use crate::{
|
||||||
|
State,
|
||||||
|
lua::{eval, exec, reload},
|
||||||
|
};
|
||||||
use azalea::{brigadier::prelude::*, chat::ChatPacket, prelude::*};
|
use azalea::{brigadier::prelude::*, chat::ChatPacket, prelude::*};
|
||||||
use futures::lock::Mutex;
|
use futures::lock::Mutex;
|
||||||
use mlua::{Error, Result, Table, UserDataRef};
|
use mlua::{Function, Table};
|
||||||
use ncr::{
|
use ncr::utils::prepend_header;
|
||||||
encoding::{Base64Encoding, Base64rEncoding, NewBase64rEncoding},
|
|
||||||
encryption::{CaesarEncryption, Cfb8Encryption, EcbEncryption, Encryption, GcmEncryption},
|
|
||||||
utils::prepend_header,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
State, crypt,
|
|
||||||
lua::{eval, exec, nochatreports::key::AesKey, reload},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub type Ctx = CommandContext<Mutex<CommandSource>>;
|
pub type Ctx = CommandContext<Mutex<CommandSource>>;
|
||||||
|
|
||||||
@@ -23,26 +18,21 @@ pub struct CommandSource {
|
|||||||
|
|
||||||
impl CommandSource {
|
impl CommandSource {
|
||||||
pub fn reply(&self, message: &str) {
|
pub fn reply(&self, message: &str) {
|
||||||
fn encrypt(options: &Table, plaintext: &str) -> Result<String> {
|
|
||||||
Ok(crypt!(encrypt, options, &prepend_header(plaintext)))
|
|
||||||
}
|
|
||||||
|
|
||||||
for mut chunk in message
|
for mut chunk in message
|
||||||
.chars()
|
.chars()
|
||||||
.collect::<Vec<char>>()
|
.collect::<Vec<char>>()
|
||||||
.chunks(if self.ncr_options.is_some() { 150 } else { 236 })
|
.chunks(if self.ncr_options.is_some() { 150 } else { 236 })
|
||||||
.map(|chars| chars.iter().collect::<String>())
|
.map(|chars| chars.iter().collect::<String>())
|
||||||
{
|
{
|
||||||
if let Some(ciphertext) = self
|
if let Some(options) = &self.ncr_options
|
||||||
.ncr_options
|
&& let Ok(encrypt) = self.state.lua.globals().get::<Function>("ncr_encrypt")
|
||||||
.as_ref()
|
&& let Ok(ciphertext) = encrypt.call::<String>((options, prepend_header(&chunk)))
|
||||||
.and_then(|options| encrypt(options, &chunk).ok())
|
|
||||||
{
|
{
|
||||||
chunk = ciphertext;
|
chunk = ciphertext;
|
||||||
}
|
}
|
||||||
self.client.chat(
|
self.client.chat(
|
||||||
&(if self.message.is_whisper()
|
&(if self.message.is_whisper()
|
||||||
&& let Some(username) = self.message.sender()
|
&& let Some(username) = self.message.username()
|
||||||
{
|
{
|
||||||
format!("/w {username} {chunk}")
|
format!("/w {username} {chunk}")
|
||||||
} else {
|
} else {
|
||||||
@@ -58,10 +48,10 @@ pub fn register(commands: &mut CommandDispatcher<Mutex<CommandSource>>) {
|
|||||||
let source = ctx.source.clone();
|
let source = ctx.source.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let source = source.lock().await;
|
let source = source.lock().await;
|
||||||
source.reply(
|
source.reply(&format!(
|
||||||
&reload(&source.state.lua, source.message.sender())
|
"{:?}",
|
||||||
.map_or_else(|error| error.to_string(), |()| String::from("ok")),
|
reload(&source.state.lua, source.message.username())
|
||||||
);
|
));
|
||||||
});
|
});
|
||||||
1
|
1
|
||||||
}));
|
}));
|
||||||
@@ -72,11 +62,10 @@ pub fn register(commands: &mut CommandDispatcher<Mutex<CommandSource>>) {
|
|||||||
let code = get_string(ctx, "code").expect("argument should exist");
|
let code = get_string(ctx, "code").expect("argument should exist");
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let source = source.lock().await;
|
let source = source.lock().await;
|
||||||
source.reply(
|
source.reply(&format!(
|
||||||
&eval(&source.state.lua, &code, source.message.sender())
|
"{:?}",
|
||||||
.await
|
eval(&source.state.lua, &code, source.message.username()).await
|
||||||
.unwrap_or_else(|error| error.to_string()),
|
));
|
||||||
);
|
|
||||||
});
|
});
|
||||||
1
|
1
|
||||||
})),
|
})),
|
||||||
@@ -88,11 +77,10 @@ pub fn register(commands: &mut CommandDispatcher<Mutex<CommandSource>>) {
|
|||||||
let code = get_string(ctx, "code").expect("argument should exist");
|
let code = get_string(ctx, "code").expect("argument should exist");
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let source = source.lock().await;
|
let source = source.lock().await;
|
||||||
source.reply(
|
source.reply(&format!(
|
||||||
&exec(&source.state.lua, &code, source.message.sender())
|
"{:?}",
|
||||||
.await
|
exec(&source.state.lua, &code, source.message.username()).await
|
||||||
.map_or_else(|error| error.to_string(), |()| String::from("ok")),
|
));
|
||||||
);
|
|
||||||
});
|
});
|
||||||
1
|
1
|
||||||
})),
|
})),
|
||||||
|
@@ -1,5 +1,11 @@
|
|||||||
use std::{net::SocketAddr, process::exit};
|
use crate::{
|
||||||
|
State,
|
||||||
|
commands::CommandSource,
|
||||||
|
http::serve,
|
||||||
|
lua::{client, direction::Direction, player::Player, vec3::Vec3},
|
||||||
|
particle,
|
||||||
|
replay::recorder::Recorder,
|
||||||
|
};
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use azalea::{
|
use azalea::{
|
||||||
brigadier::exceptions::BuiltInExceptions::DispatcherUnknownCommand, prelude::*,
|
brigadier::exceptions::BuiltInExceptions::DispatcherUnknownCommand, prelude::*,
|
||||||
@@ -10,20 +16,13 @@ use hyper_util::rt::TokioIo;
|
|||||||
use log::{debug, error, info, trace};
|
use log::{debug, error, info, trace};
|
||||||
use mlua::{Error, Function, IntoLuaMulti, Table};
|
use mlua::{Error, Function, IntoLuaMulti, Table};
|
||||||
use ncr::utils::trim_header;
|
use ncr::utils::trim_header;
|
||||||
|
use std::{net::SocketAddr, process::exit};
|
||||||
use tokio::net::TcpListener;
|
use tokio::net::TcpListener;
|
||||||
|
|
||||||
#[cfg(feature = "matrix")]
|
#[cfg(feature = "matrix")]
|
||||||
use {crate::matrix, std::time::Duration, tokio::time::sleep};
|
use crate::matrix;
|
||||||
|
|
||||||
use crate::{
|
#[allow(clippy::too_many_lines)]
|
||||||
State,
|
|
||||||
commands::CommandSource,
|
|
||||||
http::serve,
|
|
||||||
lua::{client, direction::Direction, player::Player, vec3::Vec3},
|
|
||||||
particle,
|
|
||||||
replay::recorder::Recorder,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
|
|
||||||
pub async fn handle_event(client: Client, event: Event, state: State) -> Result<()> {
|
pub async fn handle_event(client: Client, event: Event, state: State) -> Result<()> {
|
||||||
match event {
|
match event {
|
||||||
Event::AddPlayer(player_info) => {
|
Event::AddPlayer(player_info) => {
|
||||||
@@ -32,7 +31,7 @@ pub async fn handle_event(client: Client, event: Event, state: State) -> Result<
|
|||||||
Event::Chat(message) => {
|
Event::Chat(message) => {
|
||||||
let globals = state.lua.globals();
|
let globals = state.lua.globals();
|
||||||
let (sender, mut content) = message.split_sender_and_content();
|
let (sender, mut content) = message.split_sender_and_content();
|
||||||
let uuid = message.sender_uuid().map(|uuid| uuid.to_string());
|
let uuid = message.uuid().map(|uuid| uuid.to_string());
|
||||||
let is_whisper = message.is_whisper();
|
let is_whisper = message.is_whisper();
|
||||||
let text = message.message();
|
let text = message.message();
|
||||||
let ansi_text = text.to_ansi();
|
let ansi_text = text.to_ansi();
|
||||||
@@ -47,7 +46,7 @@ pub async fn handle_event(client: Client, event: Event, state: State) -> Result<
|
|||||||
.call::<String>((options.clone(), content.clone()))
|
.call::<String>((options.clone(), content.clone()))
|
||||||
.ok()
|
.ok()
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.and_then(|string| trim_header(string).ok())
|
.and_then(|s| trim_header(s).ok())
|
||||||
{
|
{
|
||||||
is_encrypted = true;
|
is_encrypted = true;
|
||||||
ncr_options = Some(options);
|
ncr_options = Some(options);
|
||||||
@@ -129,7 +128,6 @@ pub async fn handle_event(client: Client, event: Event, state: State) -> Result<
|
|||||||
Event::RemovePlayer(player_info) => {
|
Event::RemovePlayer(player_info) => {
|
||||||
call_listeners(&state, "remove_player", || Ok(Player::from(player_info))).await
|
call_listeners(&state, "remove_player", || Ok(Player::from(player_info))).await
|
||||||
}
|
}
|
||||||
Event::Spawn => call_listeners(&state, "spawn", || Ok(())).await,
|
|
||||||
Event::Tick => call_listeners(&state, "tick", || Ok(())).await,
|
Event::Tick => call_listeners(&state, "tick", || Ok(())).await,
|
||||||
Event::UpdatePlayer(player_info) => {
|
Event::UpdatePlayer(player_info) => {
|
||||||
call_listeners(&state, "update_player", || Ok(Player::from(player_info))).await
|
call_listeners(&state, "update_player", || Ok(Player::from(player_info))).await
|
||||||
@@ -212,12 +210,12 @@ pub async fn handle_event(client: Client, event: Event, state: State) -> Result<
|
|||||||
exit(0);
|
exit(0);
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
#[cfg(feature = "matrix")]
|
|
||||||
matrix_init(&client, state.clone());
|
|
||||||
|
|
||||||
let globals = state.lua.globals();
|
let globals = state.lua.globals();
|
||||||
lua_init(client, &state, &globals).await?;
|
lua_init(client, &state, &globals).await?;
|
||||||
|
|
||||||
|
#[cfg(feature = "matrix")]
|
||||||
|
matrix_init(state.clone(), &globals);
|
||||||
|
|
||||||
let Some(address): Option<SocketAddr> = globals
|
let Some(address): Option<SocketAddr> = globals
|
||||||
.get::<String>("HttpAddress")
|
.get::<String>("HttpAddress")
|
||||||
.ok()
|
.ok()
|
||||||
@@ -257,7 +255,6 @@ pub async fn handle_event(client: Client, event: Event, state: State) -> Result<
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => todo!(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -279,17 +276,14 @@ async fn lua_init(client: Client, state: &State, globals: &Table) -> Result<()>
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "matrix")]
|
#[cfg(feature = "matrix")]
|
||||||
fn matrix_init(client: &Client, state: State) {
|
fn matrix_init(state: State, globals: &Table) {
|
||||||
let globals = state.lua.globals();
|
if let Ok(homeserver_url) = globals.get::<String>("MatrixHomeserverUrl")
|
||||||
if let Ok(options) = globals.get::<Table>("MatrixOptions") {
|
&& let Ok(username) = globals.get::<String>("MatrixUsername")
|
||||||
let name = client.username();
|
&& let Ok(password) = globals.get::<String>("MatrixPassword")
|
||||||
|
{
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
loop {
|
if let Err(error) = matrix::login(state, homeserver_url, username, &password).await {
|
||||||
let name = name.clone();
|
error!("failed to log into matrix account: {error:?}");
|
||||||
if let Err(error) = matrix::login(&state, &options, &globals, name).await {
|
|
||||||
error!("failed to log into matrix: {error:?}");
|
|
||||||
}
|
|
||||||
sleep(Duration::from_secs(10)).await;
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -306,7 +300,7 @@ where
|
|||||||
let data = data.clone();
|
let data = data.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
if let Err(error) = callback.call_async::<()>(data).await {
|
if let Err(error) = callback.call_async::<()>(data).await {
|
||||||
error!("failed to call lua event listener {id} for {event_type}: {error}");
|
error!("failed to call lua event listener {id} for {event_type}: {error:?}");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@@ -1,20 +0,0 @@
|
|||||||
use azalea::{
|
|
||||||
Vec3,
|
|
||||||
movement::{KnockbackEvent, KnockbackType},
|
|
||||||
prelude::Component,
|
|
||||||
};
|
|
||||||
use bevy_ecs::{event::EventMutator, query::With, system::Query};
|
|
||||||
|
|
||||||
#[derive(Component)]
|
|
||||||
pub struct AntiKnockback;
|
|
||||||
|
|
||||||
pub fn anti_knockback(
|
|
||||||
mut events: EventMutator<KnockbackEvent>,
|
|
||||||
entity_query: Query<(), With<AntiKnockback>>,
|
|
||||||
) {
|
|
||||||
for event in events.read() {
|
|
||||||
if entity_query.get(event.entity).is_ok() {
|
|
||||||
event.knockback = KnockbackType::Add(Vec3::default());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,21 +0,0 @@
|
|||||||
#![allow(clippy::needless_pass_by_value)]
|
|
||||||
|
|
||||||
pub mod anti_knockback;
|
|
||||||
|
|
||||||
use anti_knockback::anti_knockback;
|
|
||||||
use azalea::{movement::handle_knockback, packet::game::process_packet_events};
|
|
||||||
use bevy_app::{App, Plugin, PreUpdate};
|
|
||||||
use bevy_ecs::schedule::IntoSystemConfigs;
|
|
||||||
|
|
||||||
pub struct HacksPlugin;
|
|
||||||
|
|
||||||
impl Plugin for HacksPlugin {
|
|
||||||
fn build(&self, app: &mut App) {
|
|
||||||
app.add_systems(
|
|
||||||
PreUpdate,
|
|
||||||
anti_knockback
|
|
||||||
.after(process_packet_events)
|
|
||||||
.before(handle_knockback),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
54
src/http.rs
54
src/http.rs
@@ -1,40 +1,38 @@
|
|||||||
|
use crate::{
|
||||||
|
State,
|
||||||
|
lua::{eval, exec, reload},
|
||||||
|
};
|
||||||
use http_body_util::{BodyExt, Empty, Full, combinators::BoxBody};
|
use http_body_util::{BodyExt, Empty, Full, combinators::BoxBody};
|
||||||
use hyper::{
|
use hyper::{
|
||||||
Error, Method, Request, Response, StatusCode,
|
Error, Method, Request, Response, StatusCode,
|
||||||
body::{Bytes, Incoming},
|
body::{Bytes, Incoming},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
|
||||||
State,
|
|
||||||
lua::{eval, exec, reload},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub async fn serve(
|
pub async fn serve(
|
||||||
request: Request<Incoming>,
|
request: Request<Incoming>,
|
||||||
state: State,
|
state: State,
|
||||||
) -> Result<Response<BoxBody<Bytes, Error>>, Error> {
|
) -> Result<Response<BoxBody<Bytes, Error>>, Error> {
|
||||||
|
macro_rules! handle_code {
|
||||||
|
($handler:ident) => {
|
||||||
|
match std::str::from_utf8(&request.into_body().collect().await?.to_bytes()) {
|
||||||
|
Ok(code) => Response::new(full(format!(
|
||||||
|
"{:#?}",
|
||||||
|
$handler(&state.lua, code, None).await
|
||||||
|
))),
|
||||||
|
Err(error) => status_code_response(
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
full(format!("invalid utf-8 data received: {error:?}")),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
Ok(match (request.method(), request.uri().path()) {
|
Ok(match (request.method(), request.uri().path()) {
|
||||||
(&Method::POST, "/reload") => Response::new(
|
(&Method::POST, "/reload") => {
|
||||||
reload(&state.lua, None).map_or_else(|error| full(error.to_string()), |()| empty()),
|
Response::new(full(format!("{:#?}", reload(&state.lua, None))))
|
||||||
),
|
}
|
||||||
(&Method::POST, "/eval") => Response::new(full(
|
(&Method::POST, "/eval") => handle_code!(eval),
|
||||||
eval(
|
(&Method::POST, "/exec") => handle_code!(exec),
|
||||||
&state.lua,
|
|
||||||
&String::from_utf8_lossy(&request.into_body().collect().await?.to_bytes()),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.unwrap_or_else(|error| error.to_string()),
|
|
||||||
)),
|
|
||||||
(&Method::POST, "/exec") => Response::new(
|
|
||||||
exec(
|
|
||||||
&state.lua,
|
|
||||||
&String::from_utf8_lossy(&request.into_body().collect().await?.to_bytes()),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.map_or_else(|error| full(error.to_string()), |()| empty()),
|
|
||||||
),
|
|
||||||
(&Method::GET, "/ping") => Response::new(full("pong!")),
|
(&Method::GET, "/ping") => Response::new(full("pong!")),
|
||||||
_ => status_code_response(StatusCode::NOT_FOUND, empty()),
|
_ => status_code_response(StatusCode::NOT_FOUND, empty()),
|
||||||
})
|
})
|
||||||
@@ -49,13 +47,13 @@ fn status_code_response(
|
|||||||
response
|
response
|
||||||
}
|
}
|
||||||
|
|
||||||
fn full<T: Into<Bytes>>(chunk: T) -> BoxBody<Bytes, Error> {
|
fn full<T: Into<Bytes>>(chunk: T) -> BoxBody<Bytes, hyper::Error> {
|
||||||
Full::new(chunk.into())
|
Full::new(chunk.into())
|
||||||
.map_err(|never| match never {})
|
.map_err(|never| match never {})
|
||||||
.boxed()
|
.boxed()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn empty() -> BoxBody<Bytes, Error> {
|
fn empty() -> BoxBody<Bytes, hyper::Error> {
|
||||||
Empty::<Bytes>::new()
|
Empty::<Bytes>::new()
|
||||||
.map_err(|never| match never {})
|
.map_err(|never| match never {})
|
||||||
.boxed()
|
.boxed()
|
||||||
|
@@ -1,3 +1,4 @@
|
|||||||
|
use super::{Client, Container, ContainerRef, ItemStack, Vec3};
|
||||||
use azalea::{
|
use azalea::{
|
||||||
BlockPos,
|
BlockPos,
|
||||||
inventory::{Inventory, Menu, Player, SlotList},
|
inventory::{Inventory, Menu, Player, SlotList},
|
||||||
@@ -7,8 +8,6 @@ use azalea::{
|
|||||||
use log::error;
|
use log::error;
|
||||||
use mlua::{Lua, Result, UserDataRef, Value};
|
use mlua::{Lua, Result, UserDataRef, Value};
|
||||||
|
|
||||||
use super::{Client, Container, ContainerRef, ItemStack, Vec3};
|
|
||||||
|
|
||||||
pub fn container(_lua: &Lua, client: &Client) -> Result<Option<ContainerRef>> {
|
pub fn container(_lua: &Lua, client: &Client) -> Result<Option<ContainerRef>> {
|
||||||
Ok(client.get_open_container().map(ContainerRef))
|
Ok(client.get_open_container().map(ContainerRef))
|
||||||
}
|
}
|
||||||
@@ -23,10 +22,9 @@ pub fn held_slot(_lua: &Lua, client: &Client) -> Result<u8> {
|
|||||||
|
|
||||||
#[allow(clippy::too_many_lines)]
|
#[allow(clippy::too_many_lines)]
|
||||||
pub fn menu(lua: &Lua, client: &Client) -> Result<Value> {
|
pub fn menu(lua: &Lua, client: &Client) -> Result<Value> {
|
||||||
fn from_slot_list<const N: usize>(slot_list: SlotList<N>) -> Vec<ItemStack> {
|
fn from_slot_list<const N: usize>(s: SlotList<N>) -> Vec<ItemStack> {
|
||||||
slot_list
|
s.iter()
|
||||||
.iter()
|
.map(|i| ItemStack(i.to_owned()))
|
||||||
.map(|item_stack| ItemStack(item_stack.to_owned()))
|
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -108,7 +106,7 @@ pub async fn open_container_at(
|
|||||||
.map(Container))
|
.map(Container))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn open_inventory(_lua: &Lua, client: &Client, (): ()) -> Result<Option<Container>> {
|
pub fn open_inventory(_lua: &Lua, client: &mut Client, _: ()) -> Result<Option<Container>> {
|
||||||
Ok(client.open_inventory().map(Container))
|
Ok(client.open_inventory().map(Container))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,3 +1,4 @@
|
|||||||
|
use super::{Client, Vec3};
|
||||||
use azalea::{
|
use azalea::{
|
||||||
BlockPos, BotClientExt,
|
BlockPos, BotClientExt,
|
||||||
protocol::packets::game::{ServerboundUseItem, s_interact::InteractionHand},
|
protocol::packets::game::{ServerboundUseItem, s_interact::InteractionHand},
|
||||||
@@ -6,14 +7,12 @@ use azalea::{
|
|||||||
use log::error;
|
use log::error;
|
||||||
use mlua::{Lua, Result, UserDataRef};
|
use mlua::{Lua, Result, UserDataRef};
|
||||||
|
|
||||||
use super::{Client, Vec3};
|
pub fn attack(_lua: &Lua, client: &mut Client, entity_id: i32) -> Result<()> {
|
||||||
|
|
||||||
pub fn attack(_lua: &Lua, client: &Client, entity_id: i32) -> Result<()> {
|
|
||||||
client.attack(MinecraftEntityId(entity_id));
|
client.attack(MinecraftEntityId(entity_id));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn block_interact(_lua: &Lua, client: &Client, position: Vec3) -> Result<()> {
|
pub fn block_interact(_lua: &Lua, client: &mut Client, position: Vec3) -> Result<()> {
|
||||||
#[allow(clippy::cast_possible_truncation)]
|
#[allow(clippy::cast_possible_truncation)]
|
||||||
client.block_interact(BlockPos::new(
|
client.block_interact(BlockPos::new(
|
||||||
position.x as i32,
|
position.x as i32,
|
||||||
@@ -45,7 +44,7 @@ pub fn set_mining(_lua: &Lua, client: &Client, mining: bool) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn start_mining(_lua: &Lua, client: &Client, position: Vec3) -> Result<()> {
|
pub fn start_mining(_lua: &Lua, client: &mut Client, position: Vec3) -> Result<()> {
|
||||||
#[allow(clippy::cast_possible_truncation)]
|
#[allow(clippy::cast_possible_truncation)]
|
||||||
client.start_mining(BlockPos::new(
|
client.start_mining(BlockPos::new(
|
||||||
position.x as i32,
|
position.x as i32,
|
||||||
|
@@ -6,17 +6,15 @@ mod movement;
|
|||||||
mod state;
|
mod state;
|
||||||
mod world;
|
mod world;
|
||||||
|
|
||||||
use std::ops::{Deref, DerefMut};
|
|
||||||
|
|
||||||
use azalea::{Client as AzaleaClient, world::MinecraftEntityId};
|
|
||||||
use mlua::{Lua, Result, UserData, UserDataFields, UserDataMethods};
|
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
container::{Container, ContainerRef, item_stack::ItemStack},
|
container::{Container, ContainerRef, item_stack::ItemStack},
|
||||||
direction::Direction,
|
direction::Direction,
|
||||||
player::Player,
|
player::Player,
|
||||||
vec3::Vec3,
|
vec3::Vec3,
|
||||||
};
|
};
|
||||||
|
use azalea::{Client as AzaleaClient, world::MinecraftEntityId};
|
||||||
|
use mlua::{Lua, Result, UserData, UserDataFields, UserDataMethods};
|
||||||
|
use std::ops::{Deref, DerefMut};
|
||||||
|
|
||||||
pub struct Client(pub Option<AzaleaClient>);
|
pub struct Client(pub Option<AzaleaClient>);
|
||||||
|
|
||||||
@@ -41,7 +39,6 @@ impl UserData for Client {
|
|||||||
f.add_field_method_get("dimension", world::dimension);
|
f.add_field_method_get("dimension", world::dimension);
|
||||||
f.add_field_method_get("direction", movement::direction);
|
f.add_field_method_get("direction", movement::direction);
|
||||||
f.add_field_method_get("eye_position", movement::eye_position);
|
f.add_field_method_get("eye_position", movement::eye_position);
|
||||||
f.add_field_method_get("go_to_reached", movement::go_to_reached);
|
|
||||||
f.add_field_method_get("has_attack_cooldown", interaction::has_attack_cooldown);
|
f.add_field_method_get("has_attack_cooldown", interaction::has_attack_cooldown);
|
||||||
f.add_field_method_get("health", state::health);
|
f.add_field_method_get("health", state::health);
|
||||||
f.add_field_method_get("held_item", container::held_item);
|
f.add_field_method_get("held_item", container::held_item);
|
||||||
@@ -59,43 +56,38 @@ impl UserData for Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn add_methods<M: UserDataMethods<Self>>(m: &mut M) {
|
fn add_methods<M: UserDataMethods<Self>>(m: &mut M) {
|
||||||
m.add_async_method("find_all_entities", world::find::all_entities);
|
m.add_async_method("find_all_entities", world::find_all_entities);
|
||||||
m.add_async_method("find_all_players", world::find::all_players);
|
m.add_async_method("find_all_players", world::find_all_players);
|
||||||
m.add_async_method("find_entities", world::find::entities);
|
m.add_async_method("find_entities", world::find_entities);
|
||||||
m.add_async_method("find_players", world::find::players);
|
m.add_async_method("find_players", world::find_players);
|
||||||
m.add_async_method("go_to", movement::go_to);
|
m.add_async_method("go_to", movement::go_to);
|
||||||
m.add_async_method(
|
|
||||||
"go_to_wait_until_reached",
|
|
||||||
movement::go_to_wait_until_reached,
|
|
||||||
);
|
|
||||||
m.add_async_method("mine", interaction::mine);
|
m.add_async_method("mine", interaction::mine);
|
||||||
m.add_async_method("open_container_at", container::open_container_at);
|
m.add_async_method("open_container_at", container::open_container_at);
|
||||||
m.add_async_method("set_client_information", state::set_client_information);
|
m.add_async_method("set_client_information", state::set_client_information);
|
||||||
m.add_async_method("start_go_to", movement::start_go_to);
|
|
||||||
m.add_method("attack", interaction::attack);
|
|
||||||
m.add_method("best_tool_for_block", world::best_tool_for_block);
|
m.add_method("best_tool_for_block", world::best_tool_for_block);
|
||||||
m.add_method("block_interact", interaction::block_interact);
|
|
||||||
m.add_method("chat", chat);
|
m.add_method("chat", chat);
|
||||||
m.add_method("disconnect", disconnect);
|
m.add_method("disconnect", disconnect);
|
||||||
m.add_method("find_blocks", world::find::blocks);
|
m.add_method("find_blocks", world::find_blocks);
|
||||||
m.add_method("get_block_state", world::get_block_state);
|
m.add_method("get_block_state", world::get_block_state);
|
||||||
m.add_method("get_fluid_state", world::get_fluid_state);
|
m.add_method("get_fluid_state", world::get_fluid_state);
|
||||||
m.add_method("jump", movement::jump);
|
|
||||||
m.add_method("look_at", movement::look_at);
|
|
||||||
m.add_method("open_inventory", container::open_inventory);
|
|
||||||
m.add_method("set_component", state::set_component);
|
m.add_method("set_component", state::set_component);
|
||||||
m.add_method("set_direction", movement::set_direction);
|
|
||||||
m.add_method("set_held_slot", container::set_held_slot);
|
m.add_method("set_held_slot", container::set_held_slot);
|
||||||
m.add_method("set_jumping", movement::set_jumping);
|
|
||||||
m.add_method("set_mining", interaction::set_mining);
|
m.add_method("set_mining", interaction::set_mining);
|
||||||
m.add_method("set_position", movement::set_position);
|
m.add_method("set_position", movement::set_position);
|
||||||
m.add_method("set_sneaking", movement::set_sneaking);
|
m.add_method("set_sneaking", movement::set_sneaking);
|
||||||
m.add_method("sprint", movement::sprint);
|
|
||||||
m.add_method("start_mining", interaction::start_mining);
|
|
||||||
m.add_method("stop_pathfinding", movement::stop_pathfinding);
|
m.add_method("stop_pathfinding", movement::stop_pathfinding);
|
||||||
m.add_method("stop_sleeping", movement::stop_sleeping);
|
m.add_method("stop_sleeping", movement::stop_sleeping);
|
||||||
m.add_method("use_item", interaction::use_item);
|
m.add_method("use_item", interaction::use_item);
|
||||||
m.add_method("walk", movement::walk);
|
m.add_method_mut("attack", interaction::attack);
|
||||||
|
m.add_method_mut("block_interact", interaction::block_interact);
|
||||||
|
m.add_method_mut("jump", movement::jump);
|
||||||
|
m.add_method_mut("look_at", movement::look_at);
|
||||||
|
m.add_method_mut("open_inventory", container::open_inventory);
|
||||||
|
m.add_method_mut("set_direction", movement::set_direction);
|
||||||
|
m.add_method_mut("set_jumping", movement::set_jumping);
|
||||||
|
m.add_method_mut("sprint", movement::sprint);
|
||||||
|
m.add_method_mut("start_mining", interaction::start_mining);
|
||||||
|
m.add_method_mut("walk", movement::walk);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,7 +96,7 @@ fn chat(_lua: &Lua, client: &Client, message: String) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn disconnect(_lua: &Lua, client: &Client, (): ()) -> Result<()> {
|
fn disconnect(_lua: &Lua, client: &Client, _: ()) -> Result<()> {
|
||||||
client.disconnect();
|
client.disconnect();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@@ -1,3 +1,4 @@
|
|||||||
|
use super::{Client, Direction, Vec3};
|
||||||
use azalea::{
|
use azalea::{
|
||||||
BlockPos, BotClientExt, SprintDirection, WalkDirection,
|
BlockPos, BotClientExt, SprintDirection, WalkDirection,
|
||||||
entity::Position,
|
entity::Position,
|
||||||
@@ -12,124 +13,6 @@ use azalea::{
|
|||||||
use log::error;
|
use log::error;
|
||||||
use mlua::{FromLua, Lua, Result, Table, UserDataRef, Value};
|
use mlua::{FromLua, Lua, Result, Table, UserDataRef, Value};
|
||||||
|
|
||||||
use super::{Client, Direction, Vec3};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct AnyGoal(Box<dyn Goal>);
|
|
||||||
|
|
||||||
impl Goal for AnyGoal {
|
|
||||||
fn success(&self, n: BlockPos) -> bool {
|
|
||||||
self.0.success(n)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn heuristic(&self, n: BlockPos) -> f32 {
|
|
||||||
self.0.heuristic(n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::cast_possible_truncation)]
|
|
||||||
fn to_goal(lua: &Lua, client: &Client, data: Table, options: &Table, kind: u8) -> Result<AnyGoal> {
|
|
||||||
let goal: Box<dyn Goal> = match kind {
|
|
||||||
1 => {
|
|
||||||
let pos = Vec3::from_lua(data.get("position")?, lua)?;
|
|
||||||
Box::new(RadiusGoal {
|
|
||||||
pos: azalea::Vec3::new(pos.x, pos.y, pos.z),
|
|
||||||
radius: data.get("radius")?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
2 => {
|
|
||||||
let pos = Vec3::from_lua(Value::Table(data), lua)?;
|
|
||||||
Box::new(ReachBlockPosGoal {
|
|
||||||
pos: BlockPos::new(pos.x as i32, pos.y as i32, pos.z as i32),
|
|
||||||
chunk_storage: client.world().read().chunks.clone(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
3 => Box::new(XZGoal {
|
|
||||||
x: data.get("x")?,
|
|
||||||
z: data.get("z")?,
|
|
||||||
}),
|
|
||||||
4 => Box::new(YGoal { y: data.get("y")? }),
|
|
||||||
_ => {
|
|
||||||
let pos = Vec3::from_lua(Value::Table(data), lua)?;
|
|
||||||
Box::new(BlockPosGoal(BlockPos::new(
|
|
||||||
pos.x as i32,
|
|
||||||
pos.y as i32,
|
|
||||||
pos.z as i32,
|
|
||||||
)))
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(AnyGoal(if options.get("inverse").unwrap_or_default() {
|
|
||||||
Box::new(InverseGoal(AnyGoal(goal)))
|
|
||||||
} else {
|
|
||||||
goal
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn go_to_reached(_lua: &Lua, client: &Client) -> Result<bool> {
|
|
||||||
Ok(client.is_goto_target_reached())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn go_to_wait_until_reached(
|
|
||||||
_lua: Lua,
|
|
||||||
client: UserDataRef<Client>,
|
|
||||||
(): (),
|
|
||||||
) -> Result<()> {
|
|
||||||
client.wait_until_goto_target_reached().await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn go_to(
|
|
||||||
lua: Lua,
|
|
||||||
client: UserDataRef<Client>,
|
|
||||||
(data, metadata): (Table, Option<Table>),
|
|
||||||
) -> Result<()> {
|
|
||||||
let metadata = metadata.unwrap_or(lua.create_table()?);
|
|
||||||
let options = metadata.get("options").unwrap_or(lua.create_table()?);
|
|
||||||
let goal = to_goal(
|
|
||||||
&lua,
|
|
||||||
&client,
|
|
||||||
data,
|
|
||||||
&options,
|
|
||||||
metadata.get("type").unwrap_or_default(),
|
|
||||||
)?;
|
|
||||||
if options.get("without_mining").unwrap_or_default() {
|
|
||||||
client.start_goto_without_mining(goal);
|
|
||||||
client.wait_until_goto_target_reached().await;
|
|
||||||
} else {
|
|
||||||
client.goto(goal).await;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn start_go_to(
|
|
||||||
lua: Lua,
|
|
||||||
client: UserDataRef<Client>,
|
|
||||||
(data, metadata): (Table, Option<Table>),
|
|
||||||
) -> Result<()> {
|
|
||||||
let metadata = metadata.unwrap_or(lua.create_table()?);
|
|
||||||
let options = metadata.get("options").unwrap_or(lua.create_table()?);
|
|
||||||
let goal = to_goal(
|
|
||||||
&lua,
|
|
||||||
&client,
|
|
||||||
data,
|
|
||||||
&options,
|
|
||||||
metadata.get("type").unwrap_or_default(),
|
|
||||||
)?;
|
|
||||||
if options.get("without_mining").unwrap_or_default() {
|
|
||||||
client.start_goto_without_mining(goal);
|
|
||||||
} else {
|
|
||||||
client.start_goto(goal);
|
|
||||||
}
|
|
||||||
while client.get_tick_broadcaster().recv().await.is_ok() {
|
|
||||||
if client.ecs.lock().get::<GotoEvent>(client.entity).is_none() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn direction(_lua: &Lua, client: &Client) -> Result<Direction> {
|
pub fn direction(_lua: &Lua, client: &Client) -> Result<Direction> {
|
||||||
let direction = client.direction();
|
let direction = client.direction();
|
||||||
Ok(Direction {
|
Ok(Direction {
|
||||||
@@ -142,7 +25,78 @@ pub fn eye_position(_lua: &Lua, client: &Client) -> Result<Vec3> {
|
|||||||
Ok(Vec3::from(client.eye_position()))
|
Ok(Vec3::from(client.eye_position()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn jump(_lua: &Lua, client: &Client, (): ()) -> Result<()> {
|
pub async fn go_to(
|
||||||
|
lua: Lua,
|
||||||
|
client: UserDataRef<Client>,
|
||||||
|
(data, metadata): (Table, Option<Table>),
|
||||||
|
) -> Result<()> {
|
||||||
|
fn goto_with_options<G: Goal + Send + Sync + 'static>(
|
||||||
|
client: &Client,
|
||||||
|
options: &Table,
|
||||||
|
goal: G,
|
||||||
|
) {
|
||||||
|
if options.get("without_mining").unwrap_or_default() {
|
||||||
|
client.goto_without_mining(goal);
|
||||||
|
} else {
|
||||||
|
client.goto(goal);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let table = metadata.unwrap_or(lua.create_table()?);
|
||||||
|
let goal_type = table.get("type").unwrap_or_default();
|
||||||
|
let options = table.get("options").unwrap_or(lua.create_table()?);
|
||||||
|
|
||||||
|
macro_rules! goto {
|
||||||
|
($goal:expr) => {
|
||||||
|
if options.get("inverse").unwrap_or_default() {
|
||||||
|
goto_with_options(&client, &options, InverseGoal($goal));
|
||||||
|
} else {
|
||||||
|
goto_with_options(&client, &options, $goal);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::cast_possible_truncation)]
|
||||||
|
match goal_type {
|
||||||
|
1 => {
|
||||||
|
let p = Vec3::from_lua(data.get("position")?, &lua)?;
|
||||||
|
goto!(RadiusGoal {
|
||||||
|
pos: azalea::Vec3::new(p.x, p.y, p.z),
|
||||||
|
radius: data.get("radius")?,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
2 => {
|
||||||
|
let p = Vec3::from_lua(Value::Table(data), &lua)?;
|
||||||
|
goto!(ReachBlockPosGoal {
|
||||||
|
pos: BlockPos::new(p.x as i32, p.y as i32, p.z as i32),
|
||||||
|
chunk_storage: client.world().read().chunks.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
3 => {
|
||||||
|
goto!(XZGoal {
|
||||||
|
x: data.get("x")?,
|
||||||
|
z: data.get("z")?,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
4 => goto!(YGoal { y: data.get("y")? }),
|
||||||
|
_ => {
|
||||||
|
let p = Vec3::from_lua(Value::Table(data), &lua)?;
|
||||||
|
goto!(BlockPosGoal(BlockPos::new(
|
||||||
|
p.x as i32, p.y as i32, p.z as i32
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
while client.get_tick_broadcaster().recv().await.is_ok() {
|
||||||
|
if client.ecs.lock().get::<GotoEvent>(client.entity).is_none() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn jump(_lua: &Lua, client: &mut Client, _: ()) -> Result<()> {
|
||||||
client.jump();
|
client.jump();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -160,7 +114,7 @@ pub fn looking_at(lua: &Lua, client: &Client) -> Result<Option<Table>> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn look_at(_lua: &Lua, client: &Client, position: Vec3) -> Result<()> {
|
pub fn look_at(_lua: &Lua, client: &mut Client, position: Vec3) -> Result<()> {
|
||||||
client.look_at(azalea::Vec3::new(position.x, position.y, position.z));
|
client.look_at(azalea::Vec3::new(position.x, position.y, position.z));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -195,12 +149,12 @@ pub fn position(_lua: &Lua, client: &Client) -> Result<Vec3> {
|
|||||||
Ok(Vec3::from(&client.component::<Position>()))
|
Ok(Vec3::from(&client.component::<Position>()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_direction(_lua: &Lua, client: &Client, direction: Direction) -> Result<()> {
|
pub fn set_direction(_lua: &Lua, client: &mut Client, direction: Direction) -> Result<()> {
|
||||||
client.set_direction(direction.y, direction.x);
|
client.set_direction(direction.y, direction.x);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_jumping(_lua: &Lua, client: &Client, jumping: bool) -> Result<()> {
|
pub fn set_jumping(_lua: &Lua, client: &mut Client, jumping: bool) -> Result<()> {
|
||||||
client.set_jumping(jumping);
|
client.set_jumping(jumping);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -229,7 +183,7 @@ pub fn set_sneaking(_lua: &Lua, client: &Client, sneaking: bool) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sprint(_lua: &Lua, client: &Client, direction: u8) -> Result<()> {
|
pub fn sprint(_lua: &Lua, client: &mut Client, direction: u8) -> Result<()> {
|
||||||
client.sprint(match direction {
|
client.sprint(match direction {
|
||||||
5 => SprintDirection::ForwardRight,
|
5 => SprintDirection::ForwardRight,
|
||||||
6 => SprintDirection::ForwardLeft,
|
6 => SprintDirection::ForwardLeft,
|
||||||
@@ -238,12 +192,12 @@ pub fn sprint(_lua: &Lua, client: &Client, direction: u8) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn stop_pathfinding(_lua: &Lua, client: &Client, (): ()) -> Result<()> {
|
pub fn stop_pathfinding(_lua: &Lua, client: &Client, _: ()) -> Result<()> {
|
||||||
client.stop_pathfinding();
|
client.stop_pathfinding();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn stop_sleeping(_lua: &Lua, client: &Client, (): ()) -> Result<()> {
|
pub fn stop_sleeping(_lua: &Lua, client: &Client, _: ()) -> Result<()> {
|
||||||
if let Err(error) = client.write_packet(ServerboundPlayerCommand {
|
if let Err(error) = client.write_packet(ServerboundPlayerCommand {
|
||||||
id: client.component::<MinecraftEntityId>(),
|
id: client.component::<MinecraftEntityId>(),
|
||||||
action: Action::StopSleeping,
|
action: Action::StopSleeping,
|
||||||
@@ -254,7 +208,7 @@ pub fn stop_sleeping(_lua: &Lua, client: &Client, (): ()) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn walk(_lua: &Lua, client: &Client, direction: u8) -> Result<()> {
|
pub fn walk(_lua: &Lua, client: &mut Client, direction: u8) -> Result<()> {
|
||||||
client.walk(match direction {
|
client.walk(match direction {
|
||||||
1 => WalkDirection::Forward,
|
1 => WalkDirection::Forward,
|
||||||
2 => WalkDirection::Backward,
|
2 => WalkDirection::Backward,
|
||||||
|
@@ -1,14 +1,14 @@
|
|||||||
|
use super::Client;
|
||||||
use azalea::{
|
use azalea::{
|
||||||
ClientInformation,
|
ClientInformation,
|
||||||
entity::metadata::{AirSupply, Score},
|
entity::metadata::{AirSupply, Score},
|
||||||
pathfinder::PathfinderDebugParticles,
|
pathfinder::PathfinderDebugParticles,
|
||||||
protocol::common::client_information::ModelCustomization,
|
protocol::common::client_information::ModelCustomization,
|
||||||
};
|
};
|
||||||
|
use azalea_hax::AntiKnockback;
|
||||||
|
use log::error;
|
||||||
use mlua::{Error, Lua, Result, Table, UserDataRef};
|
use mlua::{Error, Lua, Result, Table, UserDataRef};
|
||||||
|
|
||||||
use super::Client;
|
|
||||||
use crate::hacks::anti_knockback::AntiKnockback;
|
|
||||||
|
|
||||||
pub fn air_supply(_lua: &Lua, client: &Client) -> Result<i32> {
|
pub fn air_supply(_lua: &Lua, client: &Client) -> Result<i32> {
|
||||||
Ok(client.component::<AirSupply>().0)
|
Ok(client.component::<AirSupply>().0)
|
||||||
}
|
}
|
||||||
@@ -35,7 +35,8 @@ pub async fn set_client_information(
|
|||||||
info: Table,
|
info: Table,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let get_bool = |table: &Table, name| table.get(name).unwrap_or(true);
|
let get_bool = |table: &Table, name| table.get(name).unwrap_or(true);
|
||||||
client
|
|
||||||
|
if let Err(error) = client
|
||||||
.set_client_information(ClientInformation {
|
.set_client_information(ClientInformation {
|
||||||
allows_listing: info.get("allows_listing")?,
|
allows_listing: info.get("allows_listing")?,
|
||||||
model_customization: info
|
model_customization: info
|
||||||
@@ -54,7 +55,10 @@ pub async fn set_client_information(
|
|||||||
..ClientInformation::default()
|
..ClientInformation::default()
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(Error::external)
|
{
|
||||||
|
error!("failed to set client client information: {error:?}");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_component(
|
pub fn set_component(
|
||||||
|
@@ -1,122 +0,0 @@
|
|||||||
use azalea::{
|
|
||||||
BlockPos,
|
|
||||||
blocks::{BlockState, BlockStates},
|
|
||||||
ecs::query::{With, Without},
|
|
||||||
entity::{
|
|
||||||
Dead, EntityKind, EntityUuid, LookDirection, Pose, Position as AzaleaPosition,
|
|
||||||
metadata::{CustomName, Owneruuid, Player},
|
|
||||||
},
|
|
||||||
world::MinecraftEntityId,
|
|
||||||
};
|
|
||||||
use mlua::{Function, Lua, Result, Table, UserDataRef};
|
|
||||||
|
|
||||||
use super::{Client, Direction, Vec3};
|
|
||||||
|
|
||||||
pub fn blocks(
|
|
||||||
_lua: &Lua,
|
|
||||||
client: &Client,
|
|
||||||
(nearest_to, block_states): (Vec3, Vec<u16>),
|
|
||||||
) -> Result<Vec<Vec3>> {
|
|
||||||
#[allow(clippy::cast_possible_truncation)]
|
|
||||||
Ok(client
|
|
||||||
.world()
|
|
||||||
.read()
|
|
||||||
.find_blocks(
|
|
||||||
BlockPos::new(
|
|
||||||
nearest_to.x as i32,
|
|
||||||
nearest_to.y as i32,
|
|
||||||
nearest_to.z as i32,
|
|
||||||
),
|
|
||||||
&BlockStates {
|
|
||||||
set: block_states.iter().map(|&id| BlockState { id }).collect(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.map(Vec3::from)
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn all_entities(lua: Lua, client: UserDataRef<Client>, (): ()) -> Result<Vec<Table>> {
|
|
||||||
let mut matched = Vec::with_capacity(256);
|
|
||||||
for (position, custom_name, kind, uuid, direction, id, owner_uuid, pose) in
|
|
||||||
get_entities!(client)
|
|
||||||
{
|
|
||||||
let table = lua.create_table()?;
|
|
||||||
table.set("position", position)?;
|
|
||||||
table.set("custom_name", custom_name)?;
|
|
||||||
table.set("kind", kind)?;
|
|
||||||
table.set("uuid", uuid)?;
|
|
||||||
table.set("direction", direction)?;
|
|
||||||
table.set("id", id)?;
|
|
||||||
table.set(
|
|
||||||
"owner_uuid",
|
|
||||||
owner_uuid.and_then(|v| *v).map(|v| v.to_string()),
|
|
||||||
)?;
|
|
||||||
table.set("pose", pose)?;
|
|
||||||
matched.push(table);
|
|
||||||
}
|
|
||||||
Ok(matched)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn entities(
|
|
||||||
lua: Lua,
|
|
||||||
client: UserDataRef<Client>,
|
|
||||||
filter_fn: Function,
|
|
||||||
) -> Result<Vec<Table>> {
|
|
||||||
let mut matched = Vec::new();
|
|
||||||
for (position, custom_name, kind, uuid, direction, id, owner_uuid, pose) in
|
|
||||||
get_entities!(client)
|
|
||||||
{
|
|
||||||
let table = lua.create_table()?;
|
|
||||||
table.set("position", position)?;
|
|
||||||
table.set("custom_name", custom_name)?;
|
|
||||||
table.set("kind", kind)?;
|
|
||||||
table.set("uuid", uuid)?;
|
|
||||||
table.set("direction", direction)?;
|
|
||||||
table.set("id", id)?;
|
|
||||||
table.set(
|
|
||||||
"owner_uuid",
|
|
||||||
owner_uuid.and_then(|v| *v).map(|v| v.to_string()),
|
|
||||||
)?;
|
|
||||||
table.set("pose", pose)?;
|
|
||||||
if filter_fn.call_async::<bool>(&table).await? {
|
|
||||||
matched.push(table);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(matched)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn all_players(lua: Lua, client: UserDataRef<Client>, (): ()) -> Result<Vec<Table>> {
|
|
||||||
let mut matched = Vec::new();
|
|
||||||
for (id, uuid, kind, position, direction, pose) in get_players!(client) {
|
|
||||||
let table = lua.create_table()?;
|
|
||||||
table.set("id", id)?;
|
|
||||||
table.set("uuid", uuid)?;
|
|
||||||
table.set("kind", kind)?;
|
|
||||||
table.set("position", position)?;
|
|
||||||
table.set("direction", direction)?;
|
|
||||||
table.set("pose", pose)?;
|
|
||||||
matched.push(table);
|
|
||||||
}
|
|
||||||
Ok(matched)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn players(
|
|
||||||
lua: Lua,
|
|
||||||
client: UserDataRef<Client>,
|
|
||||||
filter_fn: Function,
|
|
||||||
) -> Result<Vec<Table>> {
|
|
||||||
let mut matched = Vec::new();
|
|
||||||
for (id, uuid, kind, position, direction, pose) in get_players!(client) {
|
|
||||||
let table = lua.create_table()?;
|
|
||||||
table.set("id", id)?;
|
|
||||||
table.set("uuid", uuid)?;
|
|
||||||
table.set("kind", kind)?;
|
|
||||||
table.set("position", position)?;
|
|
||||||
table.set("direction", direction)?;
|
|
||||||
table.set("pose", pose)?;
|
|
||||||
if filter_fn.call_async::<bool>(&table).await? {
|
|
||||||
matched.push(table);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(matched)
|
|
||||||
}
|
|
@@ -1,14 +1,23 @@
|
|||||||
#[macro_use]
|
#[macro_use]
|
||||||
mod queries;
|
mod queries;
|
||||||
pub mod find;
|
|
||||||
|
|
||||||
use azalea::{BlockPos, auto_tool::AutoToolClientExt, blocks::BlockState, world::InstanceName};
|
|
||||||
use mlua::{Lua, Result, Table};
|
|
||||||
|
|
||||||
use super::{Client, Direction, Vec3};
|
use super::{Client, Direction, Vec3};
|
||||||
|
use azalea::{
|
||||||
|
BlockPos,
|
||||||
|
auto_tool::AutoToolClientExt,
|
||||||
|
blocks::{BlockState, BlockStates},
|
||||||
|
ecs::query::{With, Without},
|
||||||
|
entity::{
|
||||||
|
Dead, EntityKind, EntityUuid, LookDirection, Pose, Position as AzaleaPosition,
|
||||||
|
metadata::{CustomName, Owneruuid, Player},
|
||||||
|
},
|
||||||
|
world::{InstanceName, MinecraftEntityId},
|
||||||
|
};
|
||||||
|
use mlua::{Function, Lua, Result, Table, UserDataRef};
|
||||||
|
|
||||||
pub fn best_tool_for_block(lua: &Lua, client: &Client, block_state: u16) -> Result<Table> {
|
pub fn best_tool_for_block(lua: &Lua, client: &Client, block_state: u16) -> Result<Table> {
|
||||||
let result = client.best_tool_in_hotbar_for_block(BlockState { id: block_state });
|
let result = client.best_tool_in_hotbar_for_block(BlockState { id: block_state });
|
||||||
|
|
||||||
let table = lua.create_table()?;
|
let table = lua.create_table()?;
|
||||||
table.set("index", result.index)?;
|
table.set("index", result.index)?;
|
||||||
table.set("percentage_per_tick", result.percentage_per_tick)?;
|
table.set("percentage_per_tick", result.percentage_per_tick)?;
|
||||||
@@ -19,6 +28,119 @@ pub fn dimension(_lua: &Lua, client: &Client) -> Result<String> {
|
|||||||
Ok(client.component::<InstanceName>().to_string())
|
Ok(client.component::<InstanceName>().to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn find_blocks(
|
||||||
|
_lua: &Lua,
|
||||||
|
client: &Client,
|
||||||
|
(nearest_to, block_states): (Vec3, Vec<u16>),
|
||||||
|
) -> Result<Vec<Vec3>> {
|
||||||
|
#[allow(clippy::cast_possible_truncation)]
|
||||||
|
Ok(client
|
||||||
|
.world()
|
||||||
|
.read()
|
||||||
|
.find_blocks(
|
||||||
|
BlockPos::new(
|
||||||
|
nearest_to.x as i32,
|
||||||
|
nearest_to.y as i32,
|
||||||
|
nearest_to.z as i32,
|
||||||
|
),
|
||||||
|
&BlockStates {
|
||||||
|
set: block_states.iter().map(|&id| BlockState { id }).collect(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map(Vec3::from)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn find_all_entities(
|
||||||
|
lua: Lua,
|
||||||
|
client: UserDataRef<Client>,
|
||||||
|
(): (),
|
||||||
|
) -> Result<Vec<Table>> {
|
||||||
|
let mut matched = Vec::with_capacity(256);
|
||||||
|
for (position, custom_name, kind, uuid, direction, id, owner_uuid, pose) in
|
||||||
|
get_entities!(client)
|
||||||
|
{
|
||||||
|
let table = lua.create_table()?;
|
||||||
|
table.set("position", position)?;
|
||||||
|
table.set("custom_name", custom_name)?;
|
||||||
|
table.set("kind", kind)?;
|
||||||
|
table.set("uuid", uuid)?;
|
||||||
|
table.set("direction", direction)?;
|
||||||
|
table.set("id", id)?;
|
||||||
|
table.set(
|
||||||
|
"owner_uuid",
|
||||||
|
owner_uuid.and_then(|v| *v).map(|v| v.to_string()),
|
||||||
|
)?;
|
||||||
|
table.set("pose", pose)?;
|
||||||
|
matched.push(table);
|
||||||
|
}
|
||||||
|
Ok(matched)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn find_entities(
|
||||||
|
lua: Lua,
|
||||||
|
client: UserDataRef<Client>,
|
||||||
|
filter_fn: Function,
|
||||||
|
) -> Result<Vec<Table>> {
|
||||||
|
let mut matched = Vec::new();
|
||||||
|
for (position, custom_name, kind, uuid, direction, id, owner_uuid, pose) in
|
||||||
|
get_entities!(client)
|
||||||
|
{
|
||||||
|
let table = lua.create_table()?;
|
||||||
|
table.set("position", position)?;
|
||||||
|
table.set("custom_name", custom_name)?;
|
||||||
|
table.set("kind", kind)?;
|
||||||
|
table.set("uuid", uuid)?;
|
||||||
|
table.set("direction", direction)?;
|
||||||
|
table.set("id", id)?;
|
||||||
|
table.set(
|
||||||
|
"owner_uuid",
|
||||||
|
owner_uuid.and_then(|v| *v).map(|v| v.to_string()),
|
||||||
|
)?;
|
||||||
|
table.set("pose", pose)?;
|
||||||
|
if filter_fn.call_async::<bool>(&table).await? {
|
||||||
|
matched.push(table);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(matched)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn find_all_players(lua: Lua, client: UserDataRef<Client>, (): ()) -> Result<Vec<Table>> {
|
||||||
|
let mut matched = Vec::new();
|
||||||
|
for (id, uuid, kind, position, direction, pose) in get_players!(client) {
|
||||||
|
let table = lua.create_table()?;
|
||||||
|
table.set("id", id)?;
|
||||||
|
table.set("uuid", uuid)?;
|
||||||
|
table.set("kind", kind)?;
|
||||||
|
table.set("position", position)?;
|
||||||
|
table.set("direction", direction)?;
|
||||||
|
table.set("pose", pose)?;
|
||||||
|
matched.push(table);
|
||||||
|
}
|
||||||
|
Ok(matched)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn find_players(
|
||||||
|
lua: Lua,
|
||||||
|
client: UserDataRef<Client>,
|
||||||
|
filter_fn: Function,
|
||||||
|
) -> Result<Vec<Table>> {
|
||||||
|
let mut matched = Vec::new();
|
||||||
|
for (id, uuid, kind, position, direction, pose) in get_players!(client) {
|
||||||
|
let table = lua.create_table()?;
|
||||||
|
table.set("id", id)?;
|
||||||
|
table.set("uuid", uuid)?;
|
||||||
|
table.set("kind", kind)?;
|
||||||
|
table.set("position", position)?;
|
||||||
|
table.set("direction", direction)?;
|
||||||
|
table.set("pose", pose)?;
|
||||||
|
if filter_fn.call_async::<bool>(&table).await? {
|
||||||
|
matched.push(table);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(matched)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_block_state(_lua: &Lua, client: &Client, position: Vec3) -> Result<Option<u16>> {
|
pub fn get_block_state(_lua: &Lua, client: &Client, position: Vec3) -> Result<Option<u16>> {
|
||||||
#[allow(clippy::cast_possible_truncation)]
|
#[allow(clippy::cast_possible_truncation)]
|
||||||
Ok(client
|
Ok(client
|
||||||
@@ -29,17 +151,17 @@ pub fn get_block_state(_lua: &Lua, client: &Client, position: Vec3) -> Result<Op
|
|||||||
position.y as i32,
|
position.y as i32,
|
||||||
position.z as i32,
|
position.z as i32,
|
||||||
))
|
))
|
||||||
.map(|block| block.id))
|
.map(|b| b.id))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::cast_possible_truncation)]
|
|
||||||
pub fn get_fluid_state(lua: &Lua, client: &Client, position: Vec3) -> Result<Option<Table>> {
|
pub fn get_fluid_state(lua: &Lua, client: &Client, position: Vec3) -> Result<Option<Table>> {
|
||||||
let fluid_state = client.world().read().get_fluid_state(&BlockPos::new(
|
#[allow(clippy::cast_possible_truncation)]
|
||||||
|
Ok(
|
||||||
|
if let Some(state) = client.world().read().get_fluid_state(&BlockPos::new(
|
||||||
position.x as i32,
|
position.x as i32,
|
||||||
position.y as i32,
|
position.y as i32,
|
||||||
position.z as i32,
|
position.z as i32,
|
||||||
));
|
)) {
|
||||||
Ok(if let Some(state) = fluid_state {
|
|
||||||
let table = lua.create_table()?;
|
let table = lua.create_table()?;
|
||||||
table.set("kind", state.kind as u8)?;
|
table.set("kind", state.kind as u8)?;
|
||||||
table.set("amount", state.amount)?;
|
table.set("amount", state.amount)?;
|
||||||
@@ -47,5 +169,6 @@ pub fn get_fluid_state(lua: &Lua, client: &Client, position: Vec3) -> Result<Opt
|
|||||||
Some(table)
|
Some(table)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
})
|
},
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
use azalea::inventory::{
|
use azalea::inventory::{
|
||||||
self,
|
self,
|
||||||
components::{Consumable, CustomName, Damage, Food, MaxDamage},
|
components::{CustomName, Damage, Food, MaxDamage},
|
||||||
};
|
};
|
||||||
use mlua::{UserData, UserDataFields, UserDataMethods};
|
use mlua::{UserData, UserDataFields, UserDataMethods};
|
||||||
|
|
||||||
@@ -32,24 +32,6 @@ impl UserData for ItemStack {
|
|||||||
.map(|data| data.components.get::<MaxDamage>().map(|d| d.amount)))
|
.map(|data| data.components.get::<MaxDamage>().map(|d| d.amount)))
|
||||||
});
|
});
|
||||||
|
|
||||||
f.add_field_method_get("consumable", |lua, this| {
|
|
||||||
Ok(
|
|
||||||
if let Some(consumable) = this
|
|
||||||
.0
|
|
||||||
.as_present()
|
|
||||||
.and_then(|data| data.components.get::<Consumable>())
|
|
||||||
{
|
|
||||||
let table = lua.create_table()?;
|
|
||||||
table.set("animation", consumable.animation as u8)?;
|
|
||||||
table.set("consume_seconds", consumable.consume_seconds)?;
|
|
||||||
table.set("has_consume_particles", consumable.has_consume_particles)?;
|
|
||||||
Some(table)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
},
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
f.add_field_method_get("food", |lua, this| {
|
f.add_field_method_get("food", |lua, this| {
|
||||||
Ok(
|
Ok(
|
||||||
if let Some(food) = this
|
if let Some(food) = this
|
||||||
@@ -71,7 +53,9 @@ impl UserData for ItemStack {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn add_methods<M: UserDataMethods<Self>>(m: &mut M) {
|
fn add_methods<M: UserDataMethods<Self>>(m: &mut M) {
|
||||||
m.add_method_mut("split", |_, this, count: u32| Ok(Self(this.0.split(count))));
|
m.add_method_mut("split", |_, this, count: u32| {
|
||||||
|
Ok(ItemStack(this.0.split(count)))
|
||||||
|
});
|
||||||
m.add_method_mut("update_empty", |_, this, (): ()| {
|
m.add_method_mut("update_empty", |_, this, (): ()| {
|
||||||
this.0.update_empty();
|
this.0.update_empty();
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@@ -1,9 +1,7 @@
|
|||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use crate::ListenerMap;
|
||||||
|
|
||||||
use futures::executor::block_on;
|
use futures::executor::block_on;
|
||||||
use mlua::{Function, Lua, Result, Table};
|
use mlua::{Function, Lua, Result, Table};
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
use crate::ListenerMap;
|
|
||||||
|
|
||||||
pub fn register_globals(lua: &Lua, globals: &Table, event_listeners: ListenerMap) -> Result<()> {
|
pub fn register_globals(lua: &Lua, globals: &Table, event_listeners: ListenerMap) -> Result<()> {
|
||||||
let m = event_listeners.clone();
|
let m = event_listeners.clone();
|
||||||
@@ -13,15 +11,13 @@ pub fn register_globals(lua: &Lua, globals: &Table, event_listeners: ListenerMap
|
|||||||
move |_, (event_type, callback, optional_id): (String, Function, Option<String>)| {
|
move |_, (event_type, callback, optional_id): (String, Function, Option<String>)| {
|
||||||
let m = m.clone();
|
let m = m.clone();
|
||||||
let id = optional_id.unwrap_or_else(|| {
|
let id = optional_id.unwrap_or_else(|| {
|
||||||
callback.info().name.unwrap_or_else(|| {
|
callback.info().name.unwrap_or(format!(
|
||||||
format!(
|
|
||||||
"anonymous @ {}",
|
"anonymous @ {}",
|
||||||
SystemTime::now()
|
SystemTime::now()
|
||||||
.duration_since(UNIX_EPOCH)
|
.duration_since(UNIX_EPOCH)
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
.as_millis()
|
.as_millis()
|
||||||
)
|
))
|
||||||
})
|
|
||||||
});
|
});
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
m.write()
|
m.write()
|
||||||
@@ -42,10 +38,12 @@ pub fn register_globals(lua: &Lua, globals: &Table, event_listeners: ListenerMap
|
|||||||
let m = m.clone();
|
let m = m.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let mut m = m.write().await;
|
let mut m = m.write().await;
|
||||||
let empty = m.get_mut(&event_type).is_some_and(|listeners| {
|
let empty = if let Some(listeners) = m.get_mut(&event_type) {
|
||||||
listeners.retain(|(id, _)| target_id != *id);
|
listeners.retain(|(id, _)| target_id != *id);
|
||||||
listeners.is_empty()
|
listeners.is_empty()
|
||||||
});
|
} else {
|
||||||
|
false
|
||||||
|
};
|
||||||
if empty {
|
if empty {
|
||||||
m.remove(&event_type);
|
m.remove(&event_type);
|
||||||
}
|
}
|
||||||
|
@@ -1,46 +1,17 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use matrix_sdk::{
|
|
||||||
Client as MatrixClient,
|
|
||||||
ruma::{RoomId, UserId},
|
|
||||||
};
|
|
||||||
use mlua::{Error, UserData, UserDataFields, UserDataMethods};
|
|
||||||
|
|
||||||
use super::room::Room;
|
use super::room::Room;
|
||||||
|
use matrix_sdk::{Client as MatrixClient, ruma::UserId};
|
||||||
|
use mlua::{Error, UserData, UserDataFields, UserDataMethods};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
pub struct Client(pub Arc<MatrixClient>);
|
pub struct Client(pub Arc<MatrixClient>);
|
||||||
|
|
||||||
impl UserData for Client {
|
impl UserData for Client {
|
||||||
fn add_fields<F: UserDataFields<Self>>(f: &mut F) {
|
fn add_fields<F: UserDataFields<Self>>(f: &mut F) {
|
||||||
f.add_field_method_get("invited_rooms", |_, this| {
|
|
||||||
Ok(this
|
|
||||||
.0
|
|
||||||
.invited_rooms()
|
|
||||||
.into_iter()
|
|
||||||
.map(Room)
|
|
||||||
.collect::<Vec<_>>())
|
|
||||||
});
|
|
||||||
f.add_field_method_get("joined_rooms", |_, this| {
|
|
||||||
Ok(this
|
|
||||||
.0
|
|
||||||
.joined_rooms()
|
|
||||||
.into_iter()
|
|
||||||
.map(Room)
|
|
||||||
.collect::<Vec<_>>())
|
|
||||||
});
|
|
||||||
f.add_field_method_get("left_rooms", |_, this| {
|
|
||||||
Ok(this
|
|
||||||
.0
|
|
||||||
.left_rooms()
|
|
||||||
.into_iter()
|
|
||||||
.map(Room)
|
|
||||||
.collect::<Vec<_>>())
|
|
||||||
});
|
|
||||||
f.add_field_method_get("rooms", |_, this| {
|
f.add_field_method_get("rooms", |_, this| {
|
||||||
Ok(this.0.rooms().into_iter().map(Room).collect::<Vec<_>>())
|
Ok(this.0.rooms().into_iter().map(Room).collect::<Vec<_>>())
|
||||||
});
|
});
|
||||||
f.add_field_method_get("user_id", |_, this| {
|
f.add_field_method_get("user_id", |_, this| {
|
||||||
Ok(this.0.user_id().map(ToString::to_string))
|
Ok(this.0.user_id().map(std::string::ToString::to_string))
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,12 +23,5 @@ impl UserData for Client {
|
|||||||
.map_err(Error::external)
|
.map_err(Error::external)
|
||||||
.map(Room)
|
.map(Room)
|
||||||
});
|
});
|
||||||
m.add_async_method("join_room_by_id", async |_, this, room_id: String| {
|
|
||||||
this.0
|
|
||||||
.join_room_by_id(&RoomId::parse(room_id).map_err(Error::external)?)
|
|
||||||
.await
|
|
||||||
.map_err(Error::external)
|
|
||||||
.map(Room)
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,12 +1,9 @@
|
|||||||
|
use super::member::Member;
|
||||||
use matrix_sdk::{
|
use matrix_sdk::{
|
||||||
RoomMemberships,
|
RoomMemberships, room::Room as MatrixRoom, ruma::events::room::message::RoomMessageEventContent,
|
||||||
room::Room as MatrixRoom,
|
|
||||||
ruma::{EventId, UserId, events::room::message::RoomMessageEventContent},
|
|
||||||
};
|
};
|
||||||
use mlua::{Error, UserData, UserDataFields, UserDataMethods};
|
use mlua::{Error, UserData, UserDataFields, UserDataMethods};
|
||||||
|
|
||||||
use super::member::Member;
|
|
||||||
|
|
||||||
pub struct Room(pub MatrixRoom);
|
pub struct Room(pub MatrixRoom);
|
||||||
|
|
||||||
impl UserData for Room {
|
impl UserData for Room {
|
||||||
@@ -20,54 +17,6 @@ impl UserData for Room {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn add_methods<M: UserDataMethods<Self>>(m: &mut M) {
|
fn add_methods<M: UserDataMethods<Self>>(m: &mut M) {
|
||||||
m.add_async_method(
|
|
||||||
"ban_user",
|
|
||||||
async |_, this, (user_id, reason): (String, Option<String>)| {
|
|
||||||
this.0
|
|
||||||
.ban_user(
|
|
||||||
&UserId::parse(user_id).map_err(Error::external)?,
|
|
||||||
reason.as_deref(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.map_err(Error::external)
|
|
||||||
},
|
|
||||||
);
|
|
||||||
m.add_async_method("get_members", async |_, this, (): ()| {
|
|
||||||
this.0
|
|
||||||
.members(RoomMemberships::all())
|
|
||||||
.await
|
|
||||||
.map_err(Error::external)
|
|
||||||
.map(|members| members.into_iter().map(Member).collect::<Vec<_>>())
|
|
||||||
});
|
|
||||||
m.add_async_method(
|
|
||||||
"kick_user",
|
|
||||||
async |_, this, (user_id, reason): (String, Option<String>)| {
|
|
||||||
this.0
|
|
||||||
.kick_user(
|
|
||||||
&UserId::parse(user_id).map_err(Error::external)?,
|
|
||||||
reason.as_deref(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.map_err(Error::external)
|
|
||||||
},
|
|
||||||
);
|
|
||||||
m.add_async_method("leave", async |_, this, (): ()| {
|
|
||||||
this.0.leave().await.map_err(Error::external)
|
|
||||||
});
|
|
||||||
m.add_async_method(
|
|
||||||
"redact",
|
|
||||||
async |_, this, (event_id, reason): (String, Option<String>)| {
|
|
||||||
this.0
|
|
||||||
.redact(
|
|
||||||
&EventId::parse(event_id).map_err(Error::external)?,
|
|
||||||
reason.as_deref(),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.map_err(Error::external)
|
|
||||||
.map(|response| response.event_id.to_string())
|
|
||||||
},
|
|
||||||
);
|
|
||||||
m.add_async_method("send", async |_, this, body: String| {
|
m.add_async_method("send", async |_, this, body: String| {
|
||||||
this.0
|
this.0
|
||||||
.send(RoomMessageEventContent::text_plain(body))
|
.send(RoomMessageEventContent::text_plain(body))
|
||||||
@@ -75,15 +24,20 @@ impl UserData for Room {
|
|||||||
.map_err(Error::external)
|
.map_err(Error::external)
|
||||||
.map(|response| response.event_id.to_string())
|
.map(|response| response.event_id.to_string())
|
||||||
});
|
});
|
||||||
m.add_async_method(
|
m.add_async_method("leave", async |_, this, (): ()| {
|
||||||
"send_html",
|
this.0.leave().await.map_err(Error::external)
|
||||||
async |_, this, (body, html_body): (String, String)| {
|
});
|
||||||
|
m.add_async_method("get_members", async |_, this, (): ()| {
|
||||||
this.0
|
this.0
|
||||||
.send(RoomMessageEventContent::text_html(body, html_body))
|
.members(RoomMemberships::all())
|
||||||
.await
|
.await
|
||||||
.map_err(Error::external)
|
.map_err(Error::external)
|
||||||
.map(|response| response.event_id.to_string())
|
.map(|members| {
|
||||||
},
|
members
|
||||||
);
|
.into_iter()
|
||||||
|
.map(|member| Member(member.clone()))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
})
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -13,16 +13,12 @@ pub mod vec3;
|
|||||||
#[cfg(feature = "matrix")]
|
#[cfg(feature = "matrix")]
|
||||||
pub mod matrix;
|
pub mod matrix;
|
||||||
|
|
||||||
use std::{
|
|
||||||
fmt::{self, Display, Formatter},
|
|
||||||
io,
|
|
||||||
};
|
|
||||||
|
|
||||||
use mlua::{Lua, Table};
|
|
||||||
|
|
||||||
use crate::{ListenerMap, build_info::built};
|
use crate::{ListenerMap, build_info::built};
|
||||||
|
use mlua::{Lua, Table};
|
||||||
|
use std::io;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
#[allow(dead_code)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
CreateEnv(mlua::Error),
|
CreateEnv(mlua::Error),
|
||||||
EvalChunk(mlua::Error),
|
EvalChunk(mlua::Error),
|
||||||
@@ -32,23 +28,6 @@ pub enum Error {
|
|||||||
ReadFile(io::Error),
|
ReadFile(io::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for Error {
|
|
||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
|
||||||
write!(
|
|
||||||
formatter,
|
|
||||||
"failed to {}",
|
|
||||||
match self {
|
|
||||||
Self::CreateEnv(error) => format!("create environment: {error}"),
|
|
||||||
Self::EvalChunk(error) => format!("evaluate chunk: {error}"),
|
|
||||||
Self::ExecChunk(error) => format!("execute chunk: {error}"),
|
|
||||||
Self::LoadChunk(error) => format!("load chunk: {error}"),
|
|
||||||
Self::MissingPath(error) => format!("get SCRIPT_PATH global: {error}"),
|
|
||||||
Self::ReadFile(error) => format!("read script file: {error}"),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn register_globals(
|
pub fn register_globals(
|
||||||
lua: &Lua,
|
lua: &Lua,
|
||||||
globals: &Table,
|
globals: &Table,
|
||||||
|
@@ -3,8 +3,9 @@ macro_rules! crypt {
|
|||||||
($op:ident, $options:expr, $text:expr) => {{
|
($op:ident, $options:expr, $text:expr) => {{
|
||||||
macro_rules! crypt_with {
|
macro_rules! crypt_with {
|
||||||
($algo:ident) => {{
|
($algo:ident) => {{
|
||||||
|
let encoding = $options.get("encoding").unwrap_or_default();
|
||||||
let key = &$options.get::<UserDataRef<AesKey>>("key")?.0;
|
let key = &$options.get::<UserDataRef<AesKey>>("key")?.0;
|
||||||
match $options.get("encoding").unwrap_or_default() {
|
match encoding {
|
||||||
1 => $algo::<Base64Encoding>::$op($text, &key),
|
1 => $algo::<Base64Encoding>::$op($text, &key),
|
||||||
2 => $algo::<Base64rEncoding>::$op($text, &key),
|
2 => $algo::<Base64rEncoding>::$op($text, &key),
|
||||||
_ => $algo::<NewBase64rEncoding>::$op($text, &key),
|
_ => $algo::<NewBase64rEncoding>::$op($text, &key),
|
||||||
|
@@ -1,12 +1,11 @@
|
|||||||
|
use log::error;
|
||||||
|
use mlua::{Lua, Result, Table};
|
||||||
use std::{
|
use std::{
|
||||||
ffi::OsString,
|
ffi::OsString,
|
||||||
process::{Command, Stdio},
|
process::{Command, Stdio},
|
||||||
thread,
|
thread,
|
||||||
};
|
};
|
||||||
|
|
||||||
use log::error;
|
|
||||||
use mlua::{Lua, Result, Table};
|
|
||||||
|
|
||||||
pub fn register_globals(lua: &Lua, globals: &Table) -> Result<()> {
|
pub fn register_globals(lua: &Lua, globals: &Table) -> Result<()> {
|
||||||
globals.set(
|
globals.set(
|
||||||
"system",
|
"system",
|
||||||
|
@@ -1,6 +1,5 @@
|
|||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use mlua::{Error, Function, Lua, Result, Table};
|
use mlua::{Error, Function, Lua, Result, Table};
|
||||||
|
use std::time::Duration;
|
||||||
use tokio::time::{sleep, timeout};
|
use tokio::time::{sleep, timeout};
|
||||||
|
|
||||||
pub fn register_globals(lua: &Lua, globals: &Table) -> Result<()> {
|
pub fn register_globals(lua: &Lua, globals: &Table) -> Result<()> {
|
||||||
|
@@ -40,7 +40,7 @@ impl From<&Position> for Vec3 {
|
|||||||
|
|
||||||
impl From<BlockPos> for Vec3 {
|
impl From<BlockPos> for Vec3 {
|
||||||
fn from(p: BlockPos) -> Self {
|
fn from(p: BlockPos) -> Self {
|
||||||
Self {
|
Vec3 {
|
||||||
x: f64::from(p.x),
|
x: f64::from(p.x),
|
||||||
y: f64::from(p.y),
|
y: f64::from(p.y),
|
||||||
z: f64::from(p.z),
|
z: f64::from(p.z),
|
||||||
|
46
src/main.rs
46
src/main.rs
@@ -1,12 +1,9 @@
|
|||||||
#![feature(if_let_guard, let_chains)]
|
#![feature(if_let_guard, let_chains)]
|
||||||
#![warn(clippy::pedantic, clippy::nursery)]
|
|
||||||
#![allow(clippy::significant_drop_tightening)]
|
|
||||||
|
|
||||||
mod arguments;
|
mod arguments;
|
||||||
mod build_info;
|
mod build_info;
|
||||||
mod commands;
|
mod commands;
|
||||||
mod events;
|
mod events;
|
||||||
mod hacks;
|
|
||||||
mod http;
|
mod http;
|
||||||
mod lua;
|
mod lua;
|
||||||
mod particle;
|
mod particle;
|
||||||
@@ -15,18 +12,12 @@ mod replay;
|
|||||||
#[cfg(feature = "matrix")]
|
#[cfg(feature = "matrix")]
|
||||||
mod matrix;
|
mod matrix;
|
||||||
|
|
||||||
use std::{
|
|
||||||
collections::HashMap,
|
|
||||||
env,
|
|
||||||
fs::{OpenOptions, read_to_string},
|
|
||||||
sync::Arc,
|
|
||||||
};
|
|
||||||
|
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
use arguments::Arguments;
|
use arguments::Arguments;
|
||||||
use azalea::{
|
use azalea::{
|
||||||
DefaultBotPlugins, DefaultPlugins, brigadier::prelude::CommandDispatcher, prelude::*,
|
DefaultBotPlugins, DefaultPlugins, brigadier::prelude::CommandDispatcher, prelude::*,
|
||||||
};
|
};
|
||||||
|
use azalea_hax::HaxPlugin;
|
||||||
use bevy_app::PluginGroup;
|
use bevy_app::PluginGroup;
|
||||||
use bevy_log::{
|
use bevy_log::{
|
||||||
LogPlugin,
|
LogPlugin,
|
||||||
@@ -36,10 +27,14 @@ use clap::Parser;
|
|||||||
use commands::{CommandSource, register};
|
use commands::{CommandSource, register};
|
||||||
use futures::lock::Mutex;
|
use futures::lock::Mutex;
|
||||||
use futures_locks::RwLock;
|
use futures_locks::RwLock;
|
||||||
use hacks::HacksPlugin;
|
|
||||||
use log::debug;
|
|
||||||
use mlua::{Function, Lua, Table};
|
use mlua::{Function, Lua, Table};
|
||||||
use replay::{plugin::RecordPlugin, recorder::Recorder};
|
use replay::{plugin::RecordPlugin, recorder::Recorder};
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
env,
|
||||||
|
fs::{OpenOptions, read_to_string},
|
||||||
|
sync::Arc,
|
||||||
|
};
|
||||||
|
|
||||||
#[cfg(feature = "mimalloc")]
|
#[cfg(feature = "mimalloc")]
|
||||||
#[global_allocator]
|
#[global_allocator]
|
||||||
@@ -48,7 +43,7 @@ static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
|||||||
type ListenerMap = Arc<RwLock<HashMap<String, Vec<(String, Function)>>>>;
|
type ListenerMap = Arc<RwLock<HashMap<String, Vec<(String, Function)>>>>;
|
||||||
|
|
||||||
#[derive(Default, Clone, Component)]
|
#[derive(Default, Clone, Component)]
|
||||||
struct State {
|
pub struct State {
|
||||||
lua: Arc<Lua>,
|
lua: Arc<Lua>,
|
||||||
event_listeners: ListenerMap,
|
event_listeners: ListenerMap,
|
||||||
commands: Arc<CommandDispatcher<Mutex<CommandSource>>>,
|
commands: Arc<CommandDispatcher<Mutex<CommandSource>>>,
|
||||||
@@ -63,28 +58,24 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
let event_listeners = Arc::new(RwLock::new(HashMap::new()));
|
let event_listeners = Arc::new(RwLock::new(HashMap::new()));
|
||||||
let lua = unsafe { Lua::unsafe_new() };
|
let lua = unsafe { Lua::unsafe_new() };
|
||||||
let globals = lua.globals();
|
let globals = lua.globals();
|
||||||
lua::register_globals(&lua, &globals, event_listeners.clone())?;
|
|
||||||
|
|
||||||
if let Some(path) = args.script {
|
lua::register_globals(&lua, &globals, event_listeners.clone())?;
|
||||||
globals.set("SCRIPT_PATH", &*path)?;
|
globals.set("SCRIPT_PATH", &*args.script)?;
|
||||||
lua.load(read_to_string(path)?).exec()?;
|
lua.load(
|
||||||
} else if let Some(code) = ["main.lua", "errornowatcher.lua"].iter().find_map(|path| {
|
read_to_string(&args.script)
|
||||||
debug!("trying to load code from {path}");
|
.with_context(|| format!("failed to read {}", args.script.display()))?,
|
||||||
globals.set("SCRIPT_PATH", *path).ok()?;
|
)
|
||||||
read_to_string(path).ok()
|
.exec()?;
|
||||||
}) {
|
|
||||||
lua.load(code).exec()?;
|
|
||||||
}
|
|
||||||
if let Some(code) = args.exec {
|
if let Some(code) = args.exec {
|
||||||
lua.load(code).exec()?;
|
lua.load(code).exec()?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let server = globals
|
let server = globals
|
||||||
.get::<String>("Server")
|
.get::<String>("Server")
|
||||||
.context("lua globals missing Server variable")?;
|
.expect("Server should be in lua globals");
|
||||||
let username = globals
|
let username = globals
|
||||||
.get::<String>("Username")
|
.get::<String>("Username")
|
||||||
.context("lua globals missing Username variable")?;
|
.expect("Username should be in lua globals");
|
||||||
|
|
||||||
let mut commands = CommandDispatcher::new();
|
let mut commands = CommandDispatcher::new();
|
||||||
register(&mut commands);
|
register(&mut commands);
|
||||||
@@ -131,10 +122,9 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
} else {
|
} else {
|
||||||
Account::offline(&username)
|
Account::offline(&username)
|
||||||
};
|
};
|
||||||
|
|
||||||
let Err(error) = ClientBuilder::new_without_plugins()
|
let Err(error) = ClientBuilder::new_without_plugins()
|
||||||
.add_plugins(DefaultBotPlugins)
|
.add_plugins(DefaultBotPlugins)
|
||||||
.add_plugins(HacksPlugin)
|
.add_plugins(HaxPlugin)
|
||||||
.add_plugins(default_plugins)
|
.add_plugins(default_plugins)
|
||||||
.add_plugins(record_plugin)
|
.add_plugins(record_plugin)
|
||||||
.set_handler(events::handle_event)
|
.set_handler(events::handle_event)
|
||||||
|
@@ -1,5 +1,8 @@
|
|||||||
use std::time::Duration;
|
use super::{COMMAND_PREFIX, Context};
|
||||||
|
use crate::{
|
||||||
|
events::call_listeners,
|
||||||
|
lua::{self, matrix::room::Room as LuaRoom},
|
||||||
|
};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use log::{debug, error};
|
use log::{debug, error};
|
||||||
use matrix_sdk::{
|
use matrix_sdk::{
|
||||||
@@ -10,14 +13,9 @@ use matrix_sdk::{
|
|||||||
message::{MessageType, OriginalSyncRoomMessageEvent, RoomMessageEventContent},
|
message::{MessageType, OriginalSyncRoomMessageEvent, RoomMessageEventContent},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
use std::time::Duration;
|
||||||
use tokio::time::sleep;
|
use tokio::time::sleep;
|
||||||
|
|
||||||
use super::Context;
|
|
||||||
use crate::{
|
|
||||||
events::call_listeners,
|
|
||||||
lua::{eval, exec, matrix::room::Room as LuaRoom, reload},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub async fn on_regular_room_message(
|
pub async fn on_regular_room_message(
|
||||||
event: OriginalSyncRoomMessageEvent,
|
event: OriginalSyncRoomMessageEvent,
|
||||||
room: Room,
|
room: Room,
|
||||||
@@ -30,8 +28,16 @@ pub async fn on_regular_room_message(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
|
|
||||||
if text_content.body.starts_with(&ctx.name) && ctx.is_owner(&event.sender.to_string()) {
|
if ctx
|
||||||
let body = text_content.body[ctx.name.len()..]
|
.state
|
||||||
|
.lua
|
||||||
|
.globals()
|
||||||
|
.get::<Vec<String>>("MatrixOwners")
|
||||||
|
.unwrap_or_default()
|
||||||
|
.contains(&event.sender.to_string())
|
||||||
|
&& text_content.body.starts_with(COMMAND_PREFIX)
|
||||||
|
{
|
||||||
|
let body = text_content.body[COMMAND_PREFIX.len()..]
|
||||||
.trim_start_matches(':')
|
.trim_start_matches(':')
|
||||||
.trim();
|
.trim();
|
||||||
let split = body.split_once(char::is_whitespace).unzip();
|
let split = body.split_once(char::is_whitespace).unzip();
|
||||||
@@ -41,25 +47,18 @@ pub async fn on_regular_room_message(
|
|||||||
|
|
||||||
let mut output = None;
|
let mut output = None;
|
||||||
match split.0.unwrap_or(body).to_lowercase().as_str() {
|
match split.0.unwrap_or(body).to_lowercase().as_str() {
|
||||||
"reload" => {
|
"reload" => output = Some(format!("{:#?}", lua::reload(&ctx.state.lua, None))),
|
||||||
output = Some(
|
|
||||||
reload(&ctx.state.lua, None)
|
|
||||||
.map_or_else(|error| error.to_string(), |()| String::from("ok")),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
"eval" if let Some(code) = code => {
|
"eval" if let Some(code) = code => {
|
||||||
output = Some(
|
output = Some(format!(
|
||||||
eval(&ctx.state.lua, code, None)
|
"{:#?}",
|
||||||
.await
|
lua::eval(&ctx.state.lua, code, None).await
|
||||||
.unwrap_or_else(|error| error.to_string()),
|
));
|
||||||
);
|
|
||||||
}
|
}
|
||||||
"exec" if let Some(code) = code => {
|
"exec" if let Some(code) = code => {
|
||||||
output = Some(
|
output = Some(format!(
|
||||||
exec(&ctx.state.lua, code, None)
|
"{:#?}",
|
||||||
.await
|
lua::exec(&ctx.state.lua, code, None).await
|
||||||
.map_or_else(|error| error.to_string(), |()| String::from("ok")),
|
));
|
||||||
);
|
|
||||||
}
|
}
|
||||||
"ping" => {
|
"ping" => {
|
||||||
room.send(RoomMessageEventContent::text_plain("pong!"))
|
room.send(RoomMessageEventContent::text_plain("pong!"))
|
||||||
@@ -95,11 +94,20 @@ pub async fn on_stripped_state_member(
|
|||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
if let Some(user_id) = client.user_id()
|
if let Some(user_id) = client.user_id()
|
||||||
&& member.state_key == user_id
|
&& member.state_key == user_id
|
||||||
&& ctx.is_owner(&member.sender.to_string())
|
&& ctx
|
||||||
|
.state
|
||||||
|
.lua
|
||||||
|
.globals()
|
||||||
|
.get::<Vec<String>>("MatrixOwners")
|
||||||
|
.unwrap_or_default()
|
||||||
|
.contains(&member.sender.to_string())
|
||||||
{
|
{
|
||||||
debug!("joining room {}", room.room_id());
|
debug!("joining room {}", room.room_id());
|
||||||
while let Err(error) = room.join().await {
|
while let Err(error) = room.join().await {
|
||||||
error!("failed to join room {}: {error:?}", room.room_id());
|
error!(
|
||||||
|
"failed to join room {}: {error:?}, retrying...",
|
||||||
|
room.room_id()
|
||||||
|
);
|
||||||
sleep(Duration::from_secs(10)).await;
|
sleep(Duration::from_secs(10)).await;
|
||||||
}
|
}
|
||||||
debug!("successfully joined room {}", room.room_id());
|
debug!("successfully joined room {}", room.room_id());
|
||||||
|
@@ -1,149 +1,57 @@
|
|||||||
mod bot;
|
mod bot;
|
||||||
mod verification;
|
mod verification;
|
||||||
|
|
||||||
use std::{path::Path, sync::Arc, time::Duration};
|
use crate::{State, lua::matrix::client::Client as LuaClient};
|
||||||
|
use anyhow::Result;
|
||||||
use anyhow::{Context as _, Result};
|
|
||||||
use bot::{on_regular_room_message, on_stripped_state_member};
|
use bot::{on_regular_room_message, on_stripped_state_member};
|
||||||
use log::{error, warn};
|
use matrix_sdk::{Client, config::SyncSettings};
|
||||||
use matrix_sdk::{
|
use std::{fs, sync::Arc};
|
||||||
Client, Error, LoopCtrl, authentication::matrix::MatrixSession, config::SyncSettings,
|
|
||||||
};
|
|
||||||
use mlua::Table;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use tokio::fs;
|
|
||||||
use verification::{on_device_key_verification_request, on_room_message_verification_request};
|
use verification::{on_device_key_verification_request, on_room_message_verification_request};
|
||||||
|
|
||||||
use crate::{State, events::call_listeners, lua::matrix::client::Client as LuaClient};
|
const COMMAND_PREFIX: &str = "ErrorNoWatcher";
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct Context {
|
pub struct Context {
|
||||||
state: State,
|
state: State,
|
||||||
name: String,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Context {
|
pub async fn login(
|
||||||
fn is_owner(&self, name: &String) -> bool {
|
state: State,
|
||||||
self.state
|
homeserver_url: String,
|
||||||
.lua
|
username: String,
|
||||||
.globals()
|
password: &str,
|
||||||
.get::<Table>("MatrixOptions")
|
|
||||||
.ok()
|
|
||||||
.and_then(|options| {
|
|
||||||
options
|
|
||||||
.get::<Vec<String>>("owners")
|
|
||||||
.ok()
|
|
||||||
.and_then(|owners| owners.contains(name).then_some(()))
|
|
||||||
})
|
|
||||||
.is_some()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Deserialize)]
|
|
||||||
struct Session {
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
sync_token: Option<String>,
|
|
||||||
user_session: MatrixSession,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn persist_sync_token(
|
|
||||||
session_file: &Path,
|
|
||||||
session: &mut Session,
|
|
||||||
sync_token: String,
|
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
session.sync_token = Some(sync_token);
|
let mut client = Client::builder().homeserver_url(homeserver_url);
|
||||||
fs::write(session_file, serde_json::to_string(&session)?).await?;
|
if let Some(db_path) = dirs::data_dir().map(|path| path.join("errornowatcher").join("matrix"))
|
||||||
Ok(())
|
&& fs::create_dir_all(&db_path).is_ok()
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn login(state: &State, options: &Table, globals: &Table, name: String) -> Result<()> {
|
|
||||||
let (homeserver_url, username, password, sync_timeout) = (
|
|
||||||
options.get::<String>("homeserver_url")?,
|
|
||||||
options.get::<String>("username")?,
|
|
||||||
&options.get::<String>("password")?,
|
|
||||||
options.get::<u64>("sync_timeout"),
|
|
||||||
);
|
|
||||||
let root_dir = dirs::data_dir()
|
|
||||||
.context("no data directory")?
|
|
||||||
.join("errornowatcher")
|
|
||||||
.join(&name)
|
|
||||||
.join("matrix");
|
|
||||||
|
|
||||||
let mut builder = Client::builder().homeserver_url(homeserver_url);
|
|
||||||
if !fs::try_exists(&root_dir).await.unwrap_or_default()
|
|
||||||
&& let Err(error) = fs::create_dir_all(&root_dir).await
|
|
||||||
{
|
{
|
||||||
warn!("failed to create directory for matrix sqlite store: {error:?}");
|
client = client.sqlite_store(db_path, None);
|
||||||
} else {
|
|
||||||
builder = builder.sqlite_store(&root_dir, None);
|
|
||||||
}
|
|
||||||
let client = builder.build().await?;
|
|
||||||
|
|
||||||
let mut sync_settings = SyncSettings::new();
|
|
||||||
if let Ok(seconds) = sync_timeout {
|
|
||||||
sync_settings = sync_settings.timeout(Duration::from_secs(seconds));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut new_session;
|
let client = Arc::new(client.build().await?);
|
||||||
let session_file = root_dir.join("session.json");
|
client
|
||||||
if let Some(session) = fs::read_to_string(&session_file)
|
.matrix_auth()
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.and_then(|data| serde_json::from_str::<Session>(&data).ok())
|
|
||||||
{
|
|
||||||
new_session = session.clone();
|
|
||||||
if let Some(sync_token) = session.sync_token {
|
|
||||||
sync_settings = sync_settings.token(sync_token);
|
|
||||||
}
|
|
||||||
client.restore_session(session.user_session).await?;
|
|
||||||
} else {
|
|
||||||
let matrix_auth = client.matrix_auth();
|
|
||||||
matrix_auth
|
|
||||||
.login_username(username, password)
|
.login_username(username, password)
|
||||||
.initial_device_display_name(&name)
|
.device_id("ERRORNOWATCHER")
|
||||||
|
.initial_device_display_name("ErrorNoWatcher")
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
new_session = Session {
|
|
||||||
user_session: matrix_auth.session().context("should have session")?,
|
|
||||||
sync_token: None,
|
|
||||||
};
|
|
||||||
fs::write(&session_file, serde_json::to_string(&new_session)?).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
client.add_event_handler_context(Context {
|
|
||||||
state: state.to_owned(),
|
|
||||||
name,
|
|
||||||
});
|
|
||||||
client.add_event_handler(on_stripped_state_member);
|
client.add_event_handler(on_stripped_state_member);
|
||||||
loop {
|
let response = client.sync_once(SyncSettings::default()).await?;
|
||||||
match client.sync_once(sync_settings.clone()).await {
|
|
||||||
Ok(response) => {
|
|
||||||
sync_settings = sync_settings.token(response.next_batch.clone());
|
|
||||||
persist_sync_token(&session_file, &mut new_session, response.next_batch).await?;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Err(error) => {
|
|
||||||
error!("failed to do initial sync: {error:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
client.add_event_handler(on_device_key_verification_request);
|
client.add_event_handler(on_device_key_verification_request);
|
||||||
client.add_event_handler(on_room_message_verification_request);
|
client.add_event_handler(on_room_message_verification_request);
|
||||||
client.add_event_handler(on_regular_room_message);
|
client.add_event_handler(on_regular_room_message);
|
||||||
|
|
||||||
let client = Arc::new(client);
|
state
|
||||||
globals.set("matrix", LuaClient(client.clone()))?;
|
.lua
|
||||||
call_listeners(state, "matrix_init", || Ok(())).await?;
|
.globals()
|
||||||
|
.set("matrix", LuaClient(client.clone()))?;
|
||||||
|
|
||||||
|
client.add_event_handler_context(Context { state });
|
||||||
client
|
client
|
||||||
.sync_with_result_callback(sync_settings, |sync_result| async {
|
.sync(SyncSettings::default().token(response.next_batch))
|
||||||
let mut new_session = new_session.clone();
|
|
||||||
persist_sync_token(&session_file, &mut new_session, sync_result?.next_batch)
|
|
||||||
.await
|
|
||||||
.map_err(|err| Error::UnknownError(err.into()))?;
|
|
||||||
Ok(LoopCtrl::Continue)
|
|
||||||
})
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@@ -31,14 +31,16 @@ async fn confirm_emojis(sas: SasVerification, emoji: [Emoji; 7]) {
|
|||||||
async fn print_devices(user_id: &UserId, client: &Client) -> Result<()> {
|
async fn print_devices(user_id: &UserId, client: &Client) -> Result<()> {
|
||||||
info!("devices of user {user_id}");
|
info!("devices of user {user_id}");
|
||||||
|
|
||||||
let own_id = client.device_id().context("missing own device id")?;
|
|
||||||
for device in client
|
for device in client
|
||||||
.encryption()
|
.encryption()
|
||||||
.get_user_devices(user_id)
|
.get_user_devices(user_id)
|
||||||
.await?
|
.await?
|
||||||
.devices()
|
.devices()
|
||||||
.filter(|device| device.device_id() != own_id)
|
|
||||||
{
|
{
|
||||||
|
if device.device_id() == client.device_id().context("missing device id")? {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
info!(
|
info!(
|
||||||
"\t{:<10} {:<30} {:<}",
|
"\t{:<10} {:<30} {:<}",
|
||||||
device.device_id(),
|
device.device_id(),
|
||||||
@@ -67,13 +69,13 @@ async fn sas_verification_handler(client: Client, sas: SasVerification) -> Resul
|
|||||||
} => {
|
} => {
|
||||||
tokio::spawn(confirm_emojis(
|
tokio::spawn(confirm_emojis(
|
||||||
sas.clone(),
|
sas.clone(),
|
||||||
emojis.context("only emoji verification supported")?.emojis,
|
emojis.context("only emojis supported")?.emojis,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
SasState::Done { .. } => {
|
SasState::Done { .. } => {
|
||||||
let device = sas.other_device();
|
let device = sas.other_device();
|
||||||
info!(
|
info!(
|
||||||
"successfully verified device {} {} with trust {:?}",
|
"successfully verified device {} {} trust {:?}",
|
||||||
device.user_id(),
|
device.user_id(),
|
||||||
device.device_id(),
|
device.device_id(),
|
||||||
device.local_trust_state()
|
device.local_trust_state()
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
use azalea::{entity::particle::Particle, registry::ParticleKind};
|
use azalea::{entity::particle::Particle, registry::ParticleKind};
|
||||||
|
|
||||||
#[allow(clippy::too_many_lines)]
|
#[allow(clippy::too_many_lines)]
|
||||||
pub const fn to_kind(particle: &Particle) -> ParticleKind {
|
pub fn to_kind(particle: &Particle) -> ParticleKind {
|
||||||
match particle {
|
match particle {
|
||||||
Particle::AngryVillager => ParticleKind::AngryVillager,
|
Particle::AngryVillager => ParticleKind::AngryVillager,
|
||||||
Particle::Block(_) => ParticleKind::Block,
|
Particle::Block(_) => ParticleKind::Block,
|
||||||
@@ -34,7 +34,6 @@ pub const fn to_kind(particle: &Particle) -> ParticleKind {
|
|||||||
Particle::Flame => ParticleKind::Flame,
|
Particle::Flame => ParticleKind::Flame,
|
||||||
Particle::CherryLeaves => ParticleKind::CherryLeaves,
|
Particle::CherryLeaves => ParticleKind::CherryLeaves,
|
||||||
Particle::PaleOakLeaves => ParticleKind::PaleOakLeaves,
|
Particle::PaleOakLeaves => ParticleKind::PaleOakLeaves,
|
||||||
Particle::TintedLeaves => ParticleKind::TintedLeaves,
|
|
||||||
Particle::SculkSoul => ParticleKind::SculkSoul,
|
Particle::SculkSoul => ParticleKind::SculkSoul,
|
||||||
Particle::SculkCharge(_) => ParticleKind::SculkCharge,
|
Particle::SculkCharge(_) => ParticleKind::SculkCharge,
|
||||||
Particle::SculkChargePop => ParticleKind::SculkChargePop,
|
Particle::SculkChargePop => ParticleKind::SculkChargePop,
|
||||||
@@ -116,6 +115,5 @@ pub const fn to_kind(particle: &Particle) -> ParticleKind {
|
|||||||
Particle::TrialOmen => ParticleKind::TrialOmen,
|
Particle::TrialOmen => ParticleKind::TrialOmen,
|
||||||
Particle::Trail => ParticleKind::Trail,
|
Particle::Trail => ParticleKind::Trail,
|
||||||
Particle::BlockCrumble => ParticleKind::BlockCrumble,
|
Particle::BlockCrumble => ParticleKind::BlockCrumble,
|
||||||
Particle::Firefly => ParticleKind::Firefly,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,39 +1,33 @@
|
|||||||
#![allow(clippy::needless_pass_by_value)]
|
#![allow(clippy::needless_pass_by_value)]
|
||||||
|
|
||||||
use std::sync::Arc;
|
use super::recorder::Recorder;
|
||||||
|
|
||||||
use azalea::{
|
use azalea::{
|
||||||
ecs::{event::EventReader, system::Query},
|
ecs::{event::EventReader, system::Query},
|
||||||
packet::{
|
packet_handling::{
|
||||||
config::ReceiveConfigPacketEvent,
|
configuration::ConfigurationEvent,
|
||||||
game::emit_receive_packet_events,
|
game::send_packet_events,
|
||||||
login::{LoginPacketEvent, process_packet_events},
|
login::{LoginPacketEvent, process_packet_events},
|
||||||
},
|
},
|
||||||
protocol::packets::login::ClientboundLoginPacket,
|
protocol::packets::login::ClientboundLoginPacket,
|
||||||
raw_connection::RawConnection,
|
raw_connection::RawConnection,
|
||||||
};
|
};
|
||||||
use bevy_app::{App, First, Plugin};
|
use bevy_app::{First, Plugin};
|
||||||
use bevy_ecs::{schedule::IntoSystemConfigs, system::ResMut};
|
use bevy_ecs::{schedule::IntoSystemConfigs, system::ResMut};
|
||||||
use log::error;
|
use log::error;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
use std::sync::Arc;
|
||||||
use super::recorder::Recorder;
|
|
||||||
|
|
||||||
pub struct RecordPlugin {
|
pub struct RecordPlugin {
|
||||||
pub recorder: Arc<Mutex<Option<Recorder>>>,
|
pub recorder: Arc<Mutex<Option<Recorder>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Plugin for RecordPlugin {
|
impl Plugin for RecordPlugin {
|
||||||
fn build(&self, app: &mut App) {
|
fn build(&self, app: &mut bevy_app::App) {
|
||||||
let recorder = self.recorder.lock().take();
|
if let Some(recorder) = self.recorder.lock().take() {
|
||||||
if let Some(recorder) = recorder {
|
|
||||||
app.insert_resource(recorder)
|
app.insert_resource(recorder)
|
||||||
.add_systems(First, record_login_packets.before(process_packet_events))
|
.add_systems(First, record_login_packets.before(process_packet_events))
|
||||||
.add_systems(First, record_configuration_packets)
|
.add_systems(First, record_configuration_packets)
|
||||||
.add_systems(
|
.add_systems(First, record_game_packets.before(send_packet_events));
|
||||||
First,
|
|
||||||
record_game_packets.before(emit_receive_packet_events),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -59,7 +53,7 @@ fn record_login_packets(
|
|||||||
|
|
||||||
fn record_configuration_packets(
|
fn record_configuration_packets(
|
||||||
recorder: Option<ResMut<Recorder>>,
|
recorder: Option<ResMut<Recorder>>,
|
||||||
mut events: EventReader<ReceiveConfigPacketEvent>,
|
mut events: EventReader<ConfigurationEvent>,
|
||||||
) {
|
) {
|
||||||
if let Some(mut recorder) = recorder {
|
if let Some(mut recorder) = recorder {
|
||||||
for event in events.read() {
|
for event in events.read() {
|
||||||
|
@@ -1,9 +1,4 @@
|
|||||||
use std::{
|
use crate::build_info;
|
||||||
fs::File,
|
|
||||||
io::{BufWriter, Write},
|
|
||||||
time::{Instant, SystemTime, UNIX_EPOCH},
|
|
||||||
};
|
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use azalea::{
|
use azalea::{
|
||||||
buf::AzaleaWriteVar,
|
buf::AzaleaWriteVar,
|
||||||
@@ -12,10 +7,13 @@ use azalea::{
|
|||||||
};
|
};
|
||||||
use log::debug;
|
use log::debug;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
use std::{
|
||||||
|
fs::File,
|
||||||
|
io::{BufWriter, Write},
|
||||||
|
time::{Instant, SystemTime, UNIX_EPOCH},
|
||||||
|
};
|
||||||
use zip::{ZipWriter, write::SimpleFileOptions};
|
use zip::{ZipWriter, write::SimpleFileOptions};
|
||||||
|
|
||||||
use crate::build_info;
|
|
||||||
|
|
||||||
#[derive(Resource)]
|
#[derive(Resource)]
|
||||||
pub struct Recorder {
|
pub struct Recorder {
|
||||||
zip_writer: BufWriter<ZipWriter<File>>,
|
zip_writer: BufWriter<ZipWriter<File>>,
|
||||||
@@ -58,7 +56,7 @@ impl Recorder {
|
|||||||
"fileFormat": "MCPR",
|
"fileFormat": "MCPR",
|
||||||
"fileFormatVersion": 14,
|
"fileFormatVersion": 14,
|
||||||
"protocol": PROTOCOL_VERSION,
|
"protocol": PROTOCOL_VERSION,
|
||||||
"generator": format!("ErrorNoWatcher {}", build_info::version_formatted()),
|
"generator": format!("errornowatcher {}", build_info::version_formatted()),
|
||||||
})
|
})
|
||||||
.to_string()
|
.to_string()
|
||||||
.as_bytes(),
|
.as_bytes(),
|
||||||
|
Reference in New Issue
Block a user