less clones

This commit is contained in:
Snowiiii 2024-09-19 23:13:45 +02:00
parent 8112f4a6d9
commit 14a13435c1
9 changed files with 56 additions and 59 deletions

View File

@ -7,12 +7,12 @@ use super::PlayerAction;
#[packet(0x3E)] #[packet(0x3E)]
pub struct CPlayerInfoUpdate<'a> { pub struct CPlayerInfoUpdate<'a> {
pub actions: i8, pub actions: i8,
pub players: &'a [Player], pub players: &'a [Player<'a>],
} }
pub struct Player { pub struct Player<'a> {
pub uuid: uuid::Uuid, pub uuid: uuid::Uuid,
pub actions: Vec<PlayerAction>, pub actions: Vec<PlayerAction<'a>>,
} }
impl<'a> CPlayerInfoUpdate<'a> { impl<'a> CPlayerInfoUpdate<'a> {

View File

@ -1,9 +1,9 @@
use crate::{Property, VarInt}; use crate::{Property, VarInt};
pub enum PlayerAction { pub enum PlayerAction<'a> {
AddPlayer { AddPlayer {
name: String, name: &'a str,
properties: Vec<Property>, properties: &'a [Property],
}, },
InitializeChat(u8), InitializeChat(u8),
/// Gamemode ? /// Gamemode ?

View File

@ -26,7 +26,6 @@ pub struct PacketEncoder {
impl PacketEncoder { impl PacketEncoder {
pub fn append_packet<P: ClientPacket>(&mut self, packet: &P) -> Result<(), PacketError> { pub fn append_packet<P: ClientPacket>(&mut self, packet: &P) -> Result<(), PacketError> {
let start_len = self.buf.len(); let start_len = self.buf.len();
let mut writer = (&mut self.buf).writer(); let mut writer = (&mut self.buf).writer();
let mut packet_buf = ByteBuffer::empty(); let mut packet_buf = ByteBuffer::empty();

View File

@ -77,15 +77,15 @@ pub async fn authenticate(
match response.status() { match response.status() {
StatusCode::OK => {} StatusCode::OK => {}
StatusCode::NO_CONTENT => Err(AuthError::UnverifiedUsername)?, StatusCode::NO_CONTENT => Err(AuthError::UnverifiedUsername)?,
other => Err(AuthError::UnknownStatusCode(other.as_str().to_string()))?, other => Err(AuthError::UnknownStatusCode(other))?,
} }
let profile: GameProfile = response.json().await.map_err(|_| AuthError::FailedParse)?; let profile: GameProfile = response.json().await.map_err(|_| AuthError::FailedParse)?;
Ok(profile) Ok(profile)
} }
pub fn unpack_textures(property: Property, config: &TextureConfig) -> Result<(), TextureError> { pub fn unpack_textures(property: &Property, config: &TextureConfig) -> Result<(), TextureError> {
let from64 = general_purpose::STANDARD let from64 = general_purpose::STANDARD
.decode(property.value) .decode(&property.value)
.map_err(|e| TextureError::DecodeError(e.to_string()))?; .map_err(|e| TextureError::DecodeError(e.to_string()))?;
let textures: ProfileTextures = let textures: ProfileTextures =
serde_json::from_slice(&from64).map_err(|e| TextureError::JSONError(e.to_string()))?; serde_json::from_slice(&from64).map_err(|e| TextureError::JSONError(e.to_string()))?;
@ -120,7 +120,7 @@ pub enum AuthError {
#[error("Failed to parse JSON into Game Profile")] #[error("Failed to parse JSON into Game Profile")]
FailedParse, FailedParse,
#[error("Unknown Status Code")] #[error("Unknown Status Code")]
UnknownStatusCode(String), UnknownStatusCode(StatusCode),
} }
#[derive(Error, Debug)] #[derive(Error, Debug)]

View File

@ -135,13 +135,12 @@ impl Client {
self.kick("Your account can't join"); self.kick("Your account can't join");
} }
} else { } else {
for allowed in ADVANCED_CONFIG for allowed in &ADVANCED_CONFIG
.authentication .authentication
.player_profile .player_profile
.allowed_actions .allowed_actions
.clone()
{ {
if !p.contains(&allowed) { if !p.contains(allowed) {
self.kick("Your account can't join"); self.kick("Your account can't join");
} }
} }
@ -152,7 +151,7 @@ impl Client {
Err(e) => self.kick(&e.to_string()), Err(e) => self.kick(&e.to_string()),
} }
} }
for property in gameprofile.as_ref().unwrap().properties.clone() { for property in &gameprofile.as_ref().unwrap().properties {
// TODO: use this (this was the todo here before, ill add it again cuz its prob here for a reason) // TODO: use this (this was the todo here before, ill add it again cuz its prob here for a reason)
let _ = unpack_textures(property, &ADVANCED_CONFIG.authentication.textures); let _ = unpack_textures(property, &ADVANCED_CONFIG.authentication.textures);
} }
@ -165,7 +164,7 @@ impl Client {
self.set_compression(Some((threshold, level))); self.set_compression(Some((threshold, level)));
} }
if let Some(profile) = gameprofile.as_ref().cloned() { if let Some(profile) = gameprofile.as_ref() {
let packet = CLoginSuccess::new(&profile.id, &profile.name, &profile.properties, false); let packet = CLoginSuccess::new(&profile.id, &profile.name, &profile.properties, false);
self.send_packet(&packet); self.send_packet(&packet);
} else { } else {
@ -222,16 +221,23 @@ impl Client {
client_information: SClientInformationConfig, client_information: SClientInformationConfig,
) { ) {
dbg!("got client settings"); dbg!("got client settings");
*self.config.lock() = Some(PlayerConfig { if let (Some(main_hand), Some(chat_mode)) = (
locale: client_information.locale, Hand::from_i32(client_information.main_hand.into()),
view_distance: client_information.view_distance, ChatMode::from_i32(client_information.chat_mode.into()),
chat_mode: ChatMode::from_i32(client_information.chat_mode.into()).unwrap(), ) {
chat_colors: client_information.chat_colors, *self.config.lock() = Some(PlayerConfig {
skin_parts: client_information.skin_parts, locale: client_information.locale,
main_hand: Hand::from_i32(client_information.main_hand.into()).unwrap(), view_distance: client_information.view_distance,
text_filtering: client_information.text_filtering, chat_mode,
server_listing: client_information.server_listing, chat_colors: client_information.chat_colors,
}); skin_parts: client_information.skin_parts,
main_hand,
text_filtering: client_information.text_filtering,
server_listing: client_information.server_listing,
});
} else {
self.kick("Invalid hand or chat type")
}
} }
pub fn handle_plugin_message(&self, _server: &Arc<Server>, plugin_message: SPluginMessage) { pub fn handle_plugin_message(&self, _server: &Arc<Server>, plugin_message: SPluginMessage) {

View File

@ -16,10 +16,9 @@ use authentication::GameProfile;
use crossbeam::atomic::AtomicCell; use crossbeam::atomic::AtomicCell;
use mio::{event::Event, net::TcpStream, Token}; use mio::{event::Event, net::TcpStream, Token};
use parking_lot::Mutex; use parking_lot::Mutex;
use pumpkin_core::text::TextComponent;
use pumpkin_protocol::{ use pumpkin_protocol::{
bytebuf::{packet_id::Packet, DeserializerError}, bytebuf::{packet_id::Packet, DeserializerError},
client::{config::CConfigDisconnect, login::CLoginDisconnect, play::CPlayDisconnect}, client::{config::CConfigDisconnect, login::CLoginDisconnect},
packet_decoder::PacketDecoder, packet_decoder::PacketDecoder,
packet_encoder::PacketEncoder, packet_encoder::PacketEncoder,
server::{ server::{
@ -366,11 +365,6 @@ impl Client {
self.try_send_packet(&CConfigDisconnect::new(reason)) self.try_send_packet(&CConfigDisconnect::new(reason))
.unwrap_or_else(|_| self.close()); .unwrap_or_else(|_| self.close());
} }
// So we can also kick on errors, but generally should use Player::kick
ConnectionState::Play => {
self.try_send_packet(&CPlayDisconnect::new(&TextComponent::text(reason)))
.unwrap_or_else(|_| self.close());
}
_ => { _ => {
log::warn!("Can't kick in {:?} State", self.connection_state) log::warn!("Can't kick in {:?} State", self.connection_state)
} }

View File

@ -326,7 +326,7 @@ impl Player {
Some(TextComponent::text(&message)), Some(TextComponent::text(&message)),
FilterType::PassThrough, FilterType::PassThrough,
1.into(), 1.into(),
TextComponent::text(&gameprofile.name.clone()), TextComponent::text(&gameprofile.name),
None, None,
)) ))

View File

@ -85,10 +85,7 @@ impl CachedStatus {
} }
fn load_icon(path: &str) -> String { fn load_icon(path: &str) -> String {
let icon = match image::open(path).map_err(|e| panic!("error loading icon: {}", e)) { let icon = image::open(path).expect("Failed to load icon");
Ok(icon) => icon,
Err(_) => return "".into(),
};
let dimension = icon.dimensions(); let dimension = icon.dimensions();
assert!(dimension.0 == 64, "Icon width must be 64"); assert!(dimension.0 == 64, "Icon width must be 64");
assert!(dimension.1 == 64, "Icon height must be 64"); assert!(dimension.1 == 64, "Icon height must be 64");

View File

@ -129,8 +129,8 @@ impl World {
uuid: gameprofile.id, uuid: gameprofile.id,
actions: vec![ actions: vec![
PlayerAction::AddPlayer { PlayerAction::AddPlayer {
name: gameprofile.name.clone(), name: &gameprofile.name,
properties: gameprofile.properties.clone(), properties: &gameprofile.properties,
}, },
PlayerAction::UpdateListed(true), PlayerAction::UpdateListed(true),
], ],
@ -139,27 +139,28 @@ impl World {
// here we send all the infos of already joined players // here we send all the infos of already joined players
let mut entries = Vec::new(); let mut entries = Vec::new();
for (_, playerr) in self
.current_players
.lock()
.iter()
.filter(|(c, _)| **c != player.client.token)
{ {
let gameprofile = &playerr.gameprofile; let current_players = self.current_players.lock();
entries.push(pumpkin_protocol::client::play::Player { for (_, playerr) in current_players
uuid: gameprofile.id, .iter()
actions: vec![ .filter(|(c, _)| **c != player.client.token)
PlayerAction::AddPlayer { {
name: gameprofile.name.clone(), let gameprofile = &playerr.gameprofile;
properties: gameprofile.properties.clone(), entries.push(pumpkin_protocol::client::play::Player {
}, uuid: gameprofile.id,
PlayerAction::UpdateListed(true), actions: vec![
], PlayerAction::AddPlayer {
}) name: &gameprofile.name,
properties: &gameprofile.properties,
},
PlayerAction::UpdateListed(true),
],
})
}
player
.client
.send_packet(&CPlayerInfoUpdate::new(0x01 | 0x08, &entries));
} }
player
.client
.send_packet(&CPlayerInfoUpdate::new(0x01 | 0x08, &entries));
let gameprofile = &player.gameprofile; let gameprofile = &player.gameprofile;