azalea_client/plugins/
disconnect.rs1use azalea_chat::FormattedText;
4use azalea_entity::{EntityBundle, InLoadedChunk, LocalEntity, metadata::PlayerMetadataBundle};
5use azalea_world::MinecraftEntityId;
6use bevy_app::{App, Plugin, PostUpdate};
7use bevy_ecs::prelude::*;
8use derive_more::Deref;
9use tracing::info;
10
11use super::login::IsAuthenticated;
12use crate::{
13 chat_signing, client::JoinedClientBundle, connection::RawConnection, loading::HasClientLoaded,
14 local_player::InstanceHolder,
15};
16
17pub struct DisconnectPlugin;
18impl Plugin for DisconnectPlugin {
19 fn build(&self, app: &mut App) {
20 app.add_event::<DisconnectEvent>().add_systems(
21 PostUpdate,
22 (
23 update_read_packets_task_running_component,
24 remove_components_from_disconnected_players,
25 disconnect_on_connection_dead,
30 )
31 .chain(),
32 );
33 }
34}
35
36#[derive(Event)]
47pub struct DisconnectEvent {
48 pub entity: Entity,
49 pub reason: Option<FormattedText>,
50}
51
52#[derive(Bundle)]
57pub struct RemoveOnDisconnectBundle {
58 pub joined_client: JoinedClientBundle,
59
60 pub entity: EntityBundle,
61 pub minecraft_entity_id: MinecraftEntityId,
62 pub instance_holder: InstanceHolder,
63 pub player_metadata: PlayerMetadataBundle,
64 pub in_loaded_chunk: InLoadedChunk,
65 pub raw_connection: RawConnection,
67 pub is_connection_alive: IsConnectionAlive,
69 pub chat_signing_session: chat_signing::ChatSigningSession,
71 pub is_authenticated: IsAuthenticated,
73 pub has_client_loaded: HasClientLoaded,
75}
76
77pub fn remove_components_from_disconnected_players(
80 mut commands: Commands,
81 mut events: EventReader<DisconnectEvent>,
82 mut loaded_by_query: Query<&mut azalea_entity::LoadedBy>,
83) {
84 for DisconnectEvent { entity, reason } in events.read() {
85 info!(
86 "A client {entity:?} was disconnected{}",
87 if let Some(reason) = reason {
88 format!(": {reason}")
89 } else {
90 "".to_string()
91 }
92 );
93 commands
94 .entity(*entity)
95 .remove::<RemoveOnDisconnectBundle>();
96 for mut loaded_by in &mut loaded_by_query.iter_mut() {
103 loaded_by.remove(entity);
104 }
105 }
106}
107
108#[derive(Component, Clone, Copy, Debug, Deref)]
109pub struct IsConnectionAlive(bool);
110
111fn update_read_packets_task_running_component(
112 query: Query<(Entity, &RawConnection)>,
113 mut commands: Commands,
114) {
115 for (entity, raw_connection) in &query {
116 let running = raw_connection.is_alive();
117 commands.entity(entity).insert(IsConnectionAlive(running));
118 }
119}
120
121#[allow(clippy::type_complexity)]
122fn disconnect_on_connection_dead(
123 query: Query<(Entity, &IsConnectionAlive), (Changed<IsConnectionAlive>, With<LocalEntity>)>,
124 mut disconnect_events: EventWriter<DisconnectEvent>,
125) {
126 for (entity, &is_connection_alive) in &query {
127 if !*is_connection_alive {
128 disconnect_events.write(DisconnectEvent {
129 entity,
130 reason: None,
131 });
132 }
133 }
134}