RemoteFriendListUpdateHandler .java

net.minecraft.client.gui.screens.social.RemoteFriendListUpdateHandler (class): members: BACKGROUND_INTERVAL_MULTIPLIER, FOREGROUND_INTERVAL_NANOS, enabled.

net.minecraft.client.gui.screens.socialclass262 linesclient9.6 KB

API Surface (8)

FriendData getLatestFriendData()
RemoteFriendListUpdateHandler.State getState()
void addUpdateListener(final Runnable listener)
void removeUpdateListener(final Runnable listener)
CompletableFuture<Void> forceUpdate()
void start()
void stop()
void close()

Fields & Constants (17)

LOGGER
FOREGROUND_INTERVAL_NANOS
BACKGROUND_INTERVAL_MULTIPLIER
POLL_INTERVAL_SECONDS
friendsService
minecraft
scheduler
updateInProgress
enabled
updateListeners
lastUpdateNanos
latestFriendData
state
knownFriends
knownIncoming
knownOutgoing
scheduledTick

String literals (5)

"Friends List"
"Performing Friends List update"
"Failed to update friend data"
"Friends List callback failed"
"Failed to schedule forced Friends List update"

Code Graph: Dependencies (4)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

RemoteFriendListUpdateHandler.java262 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.client.gui.screens.social;
2
3
import com.mojang.authlib.services.FriendsService;
4
import com.mojang.authlib.services.FriendsService.ResultCode;
5
import com.mojang.authlib.services.response.FriendData;
6
import com.mojang.authlib.services.response.FriendDto;
7
import com.mojang.logging.LogUtils;
8
import java.time.Duration;
9
import java.util.HashSet;
10
import java.util.Set;
11
import java.util.UUID;
12
import java.util.concurrent.CompletableFuture;
13
import java.util.concurrent.CopyOnWriteArraySet;
14
import java.util.concurrent.Executors;
15
import java.util.concurrent.ScheduledExecutorService;
16
import java.util.concurrent.ScheduledFuture;
17
import java.util.concurrent.TimeUnit;
18
import java.util.concurrent.atomic.AtomicBoolean;
19
import java.util.concurrent.atomic.AtomicReference;
20
import net.fabricmc.api.EnvType;
21
import net.fabricmc.api.Environment;
22
import net.minecraft.client.Minecraft;
23
import net.minecraft.client.gui.components.toasts.FriendToast;
24
import net.minecraft.client.gui.screens.Screen;
25
import net.minecraft.client.gui.screens.friends.FriendsOverlayScreen;
26
import org.jspecify.annotations.Nullable;
27
import org.slf4j.Logger;
28
29
@Environment(EnvType.CLIENT)
30
public final class RemoteFriendListUpdateHandler {
31
	private static final Logger LOGGER = LogUtils.getLogger();
32
	private static final long FOREGROUND_INTERVAL_NANOS = TimeUnit.MINUTES.toNanos(1L);
33
	private static final long BACKGROUND_INTERVAL_MULTIPLIER = 5L;
34
	private static final long POLL_INTERVAL_SECONDS = 1L;
35
	private final FriendsService friendsService;
36
	private final Minecraft minecraft;
37
	private final ScheduledExecutorService scheduler;
38
	private final AtomicBoolean updateInProgress = new AtomicBoolean(false);
39
	private final AtomicBoolean enabled = new AtomicBoolean(false);
40
	private final Set<Runnable> updateListeners = new CopyOnWriteArraySet<>();
41
	private volatile long lastUpdateNanos = 0L;
42
	private volatile FriendData latestFriendData = FriendData.empty();
43
	private volatile RemoteFriendListUpdateHandler.State state = RemoteFriendListUpdateHandler.State.LOADING;
44
	private volatile Set<FriendDto> knownFriends = new HashSet<>();
45
	private volatile Set<FriendDto> knownIncoming = new HashSet<>();
46
	private volatile Set<FriendDto> knownOutgoing = new HashSet<>();
47
	private @Nullable ScheduledFuture<?> scheduledTick;
48
49
	public RemoteFriendListUpdateHandler(final FriendsService friendsService, final Minecraft minecraft) {
50
		this.friendsService = friendsService;
51
		this.minecraft = minecraft;
52
		this.scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
53
			Thread thread = new Thread(runnable, "Friends List");
54
			thread.setDaemon(true);
55
			return thread;
56
		});
57
	}
58
59
	private void runBackgroundTick() {
60
		if (!this.updateInProgress.get() && this.enabled.get()) {
61
			long now = System.nanoTime();
62
			if (this.lastUpdateNanos == 0L || now - this.lastUpdateNanos >= this.getUpdateIntervalNanos()) {
63
				this.runUpdateFriendDataInternal();
64
			}
65
		}
66
	}
67
68
	public FriendData getLatestFriendData() {
69
		return this.latestFriendData;
70
	}
71
72
	public RemoteFriendListUpdateHandler.State getState() {
73
		return this.state;
74
	}
75
76
	public void addUpdateListener(final Runnable listener) {
77
		this.updateListeners.add(listener);
78
	}
79
80
	public void removeUpdateListener(final Runnable listener) {
81
		this.updateListeners.remove(listener);
82
	}
83
84
	private long getUpdateIntervalNanos() {
85
		long foregroundNanos = this.friendsService.getFriendsPollInterval().map(Duration::toNanos).orElse(FOREGROUND_INTERVAL_NANOS);
86
		Screen screen = this.minecraft.gui.screen();
87
		return screen instanceof FriendsOverlayScreen ? foregroundNanos : foregroundNanos * 5L;
88
	}
89
90
	void runUpdateFriendDataInternal() {
91
		if (!this.updateInProgress.compareAndSet(false, true)) {
92
			LOGGER.debug("Attempted to run Friends List update but update is already in progress");
93
		} else {
94
			LOGGER.debug("Performing Friends List update");
95
			AtomicReference<FriendData> friendData = new AtomicReference<>(FriendData.empty());
96
			boolean shouldNotifyListeners = false;
97
98
			try {
99
				ResultCode resultCode = this.friendsService.getFriendData(friendData::set);
100
				RemoteFriendListUpdateHandler.State newState = mapResultCodeToState(resultCode);
101
				RemoteFriendListUpdateHandler.State previousState = this.state;
102
				boolean stateTransition = previousState != newState;
103
				this.state = newState;
104
				if (resultCode == ResultCode.SUCCESS) {
105
					FriendData data = friendData.get();
106
					this.latestFriendData = data;
107
					boolean dataChanged = this.detectChangesAndShowToast(data, previousState);
108
					shouldNotifyListeners = dataChanged || stateTransition;
109
					return;
110
				}
111
112
				LOGGER.warn("Friends List update failed with result code: {}", resultCode);
113
				shouldNotifyListeners = true;
114
			} catch (Throwable e) {
115
				LOGGER.warn("Failed to update friend data", e);
116
				return;
117
			} finally {
118
				this.updateInProgress.set(false);
119
				this.lastUpdateNanos = System.nanoTime();
120
				if (shouldNotifyListeners) {
121
					this.notifyListeners();
122
				}
123
			}
124
		}
125
	}
126
127
	private static RemoteFriendListUpdateHandler.State mapResultCodeToState(final ResultCode resultCode) {
128
		return switch (resultCode) {
129
			case TEMPORARY_UNAVAILABLE, FORBIDDEN, SERVICE_NOT_AVAILABLE, TOO_MANY_REQUESTS -> RemoteFriendListUpdateHandler.State.TEMPORARY_UNAVAILABLE;
130
			case CONNECTION_ISSUE -> RemoteFriendListUpdateHandler.State.CONNECTION_ISSUE;
131
			case UPGRADE_NEEDED -> RemoteFriendListUpdateHandler.State.UPGRADE_NEEDED;
132
			case UNKNOWN_PROFILE -> RemoteFriendListUpdateHandler.State.USER_MAY_LACK_ACTIVE_PROFILE;
133
			case UNAUTHORIZED -> RemoteFriendListUpdateHandler.State.UNAUTHORIZED;
134
			case GENERIC_ERROR, ERROR -> RemoteFriendListUpdateHandler.State.GENERIC_ERROR;
135
			case SUCCESS -> RemoteFriendListUpdateHandler.State.SUCCESS;
136
		};
137
	}
138
139
	private void notifyListeners() {
140
		if (!this.updateListeners.isEmpty()) {
141
			LOGGER.debug("Notifying {} Friends List update listeners", this.updateListeners.size());
142
			this.minecraft.execute(() -> {
143
				for (Runnable listener : this.updateListeners) {
144
					try {
145
						listener.run();
146
					} catch (Throwable e) {
147
						LOGGER.warn("Friends List callback failed", e);
148
					}
149
				}
150
			});
151
		}
152
	}
153
154
	private boolean detectChangesAndShowToast(final FriendData friendData, final RemoteFriendListUpdateHandler.State previousState) {
155
		Set<FriendDto> currentFriends = new HashSet<>(friendData.friends());
156
		Set<FriendDto> currentIncoming = new HashSet<>(friendData.incomingRequests());
157
		Set<FriendDto> currentOutgoing = new HashSet<>(friendData.outgoingRequests());
158
		if (previousState != RemoteFriendListUpdateHandler.State.SUCCESS) {
159
			this.knownFriends = currentFriends;
160
			this.knownIncoming = currentIncoming;
161
			this.knownOutgoing = currentOutgoing;
162
			return true;
163
		}
164
165
		if (!this.isInGameAndToastsDisabled()) {
166
			for (FriendDto friendDto : currentFriends) {
167
				if (!this.knownFriends.contains(friendDto)) {
168
					if (!this.knownOutgoing.contains(friendDto) && !this.knownIncoming.contains(friendDto)) {
169
						this.emitToastWithSkin(friendDto.profileId(), friendDto.name(), FriendToast::showFriendAdded);
170
					} else {
171
						this.emitToastWithSkin(friendDto.profileId(), friendDto.name(), FriendToast::showFriendRequestAccepted);
172
					}
173
				}
174
			}
175
176
			for (FriendDto friendDto : currentIncoming) {
177
				if (!this.knownIncoming.contains(friendDto) && !currentFriends.contains(friendDto)) {
178
					this.emitToastWithSkin(friendDto.profileId(), friendDto.name(), FriendToast::showFriendRequestReceived);
179
				}
180
			}
181
182
			for (FriendDto friendDto : currentOutgoing) {
183
				if (!this.knownOutgoing.contains(friendDto) && !currentFriends.contains(friendDto)) {
184
					this.minecraft.execute(() -> FriendToast.showFriendRequestSent(this.minecraft, friendDto.name()));
185
				}
186
			}
187
		}
188
189
		boolean hasChanges = !this.knownFriends.equals(currentFriends) || !this.knownIncoming.equals(currentIncoming) || !this.knownOutgoing.equals(currentOutgoing);
190
		this.knownFriends = currentFriends;
191
		this.knownIncoming = currentIncoming;
192
		this.knownOutgoing = currentOutgoing;
193
		return hasChanges;
194
	}
195
196
	private boolean isInGameAndToastsDisabled() {
197
		return this.minecraft.level != null && !this.minecraft.options.inGameNotification().get();
198
	}
199
200
	private void emitToastWithSkin(final UUID playerId, final String playerName, final FriendToast.SkinToastEmitter emitter) {
201
		this.minecraft.execute(() -> emitter.emit(this.minecraft, playerName, playerId));
202
	}
203
204
	public CompletableFuture<Void> forceUpdate() {
205
		if (this.enabled.get() && !this.scheduler.isShutdown()) {
206
			CompletableFuture<Void> future = new CompletableFuture<>();
207
208
			try {
209
				this.scheduler.execute(() -> {
210
					try {
211
						this.runUpdateFriendDataInternal();
212
					} finally {
213
						future.complete(null);
214
					}
215
				});
216
			} catch (Throwable e) {
217
				LOGGER.warn("Failed to schedule forced Friends List update", e);
218
				future.complete(null);
219
			}
220
221
			return future;
222
		} else {
223
			return CompletableFuture.completedFuture(null);
224
		}
225
	}
226
227
	public synchronized void start() {
228
		if (this.scheduler.isShutdown()) {
229
			LOGGER.warn("Attempted to start Friends List updater but scheduler is already shut down");
230
		} else if (this.enabled.compareAndSet(false, true)) {
231
			if (this.scheduledTick == null || this.scheduledTick.isCancelled() || this.scheduledTick.isDone()) {
232
				this.scheduledTick = this.scheduler.scheduleWithFixedDelay(this::runBackgroundTick, 0L, 1L, TimeUnit.SECONDS);
233
			}
234
		}
235
	}
236
237
	public synchronized void stop() {
238
		this.enabled.set(false);
239
		if (this.scheduledTick != null) {
240
			this.scheduledTick.cancel(false);
241
			this.scheduledTick = null;
242
		}
243
	}
244
245
	public synchronized void close() {
246
		this.stop();
247
		this.scheduler.shutdownNow();
248
	}
249
250
	@Environment(EnvType.CLIENT)
251
	public enum State {
252
		LOADING,
253
		UPGRADE_NEEDED,
254
		CONNECTION_ISSUE,
255
		USER_MAY_LACK_ACTIVE_PROFILE,
256
		UNAUTHORIZED,
257
		TEMPORARY_UNAVAILABLE,
258
		GENERIC_ERROR,
259
		SUCCESS;
260
	}
261
}
262

Decompiled Minecraft 26.3 source of RemoteFriendListUpdateHandler (net/minecraft/client/gui/screens/social/RemoteFriendListUpdateHandler.java) with Mojang official mappings, stored verbatim on the site.